import { NextRequest, NextResponse } from "next/server";

// Mark this route as dynamic (required for API routes using searchParams)
export const dynamic = "force-dynamic";

/**
 * API Route: Generate ElevenLabs Conversation Token
 *
 * This endpoint generates a secure conversation token for WebRTC connections
 * to ElevenLabs Voice Agent. The token is required for authenticated agent access.
 *
 * Security:
 * - API key is kept server-side only (never exposed to client)
 * - Rate limiting should be applied in production
 * - Consider adding user authentication if needed
 *
 * @returns Conversation token or error response
 */
export async function GET(request: NextRequest) {
  try {
    // Get agent ID from environment
    const agentId = process.env.NEXT_PUBLIC_ELEVENLABS_AGENT_ID;
    const apiKey = process.env.ELEVENLABS_API_KEY;

    // Validate environment variables
    if (!agentId) {
      console.error(
        "Missing NEXT_PUBLIC_ELEVENLABS_AGENT_ID environment variable",
      );
      return NextResponse.json(
        { error: "Voice agent configuration is missing" },
        { status: 500 },
      );
    }

    if (!apiKey) {
      console.error("Missing ELEVENLABS_API_KEY environment variable");
      return NextResponse.json(
        { error: "Voice agent authentication is not configured" },
        { status: 500 },
      );
    }

    // Optional: Extract user information from request for tracking
    // This could be used to associate conversations with specific users
    const searchParams = request.nextUrl.searchParams;
    const userId = searchParams.get("userId"); // Optional user ID

    // Static demo booking data that the agent can reference
    // This provides context about available appointments for the demo
    const demoBookingContext = {
      clinicName: "Mawidi Demo Clinic",
      availableDates: [
        { date: "2025-11-08", slots: ["09:00", "10:30", "14:00", "15:30"] },
        { date: "2025-11-09", slots: ["10:00", "11:30", "13:00", "16:00"] },
        { date: "2025-11-10", slots: ["09:30", "11:00", "14:30", "16:30"] },
      ],
      services: [
        { name: "General Consultation", price: "200 SAR", duration: "30 min" },
        {
          name: "Specialist Consultation",
          price: "400 SAR",
          duration: "45 min",
        },
        { name: "Follow-up Visit", price: "150 SAR", duration: "20 min" },
      ],
      languages: ["Arabic", "English"],
      workingHours: "9:00 AM - 5:00 PM, Saturday to Thursday",
    };

    // Request conversation token from ElevenLabs API
    const response = await fetch(
      `https://api.elevenlabs.io/v1/convai/conversation/token?agent_id=${agentId}`,
      {
        method: "GET",
        headers: {
          "xi-api-key": apiKey,
        },
      },
    );

    // Handle API errors
    if (!response.ok) {
      const errorText = await response.text();
      console.error("ElevenLabs API error:", response.status, errorText);

      return NextResponse.json(
        {
          error: "Failed to generate conversation token",
          details:
            response.status === 401 ? "Invalid API key" : "Service unavailable",
        },
        { status: response.status },
      );
    }

    // Parse response
    const data = await response.json();

    // Return token and optional context
    return NextResponse.json({
      token: data.token,
      agentId,
      // Include demo context for reference (optional)
      demoContext: demoBookingContext,
      userId: userId || undefined,
    });
  } catch (error) {
    console.error("Error generating conversation token:", error);

    return NextResponse.json(
      {
        error: "Internal server error",
        message: error instanceof Error ? error.message : "Unknown error",
      },
      { status: 500 },
    );
  }
}

/**
 * Health check endpoint
 */
export async function HEAD() {
  return new NextResponse(null, { status: 200 });
}
