import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/admin-auth";
import { sql } from "@/db";

// Get tickets or responses for a specific ticket
export async function GET(request: Request) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const { searchParams } = new URL(request.url);
    const ticketId = searchParams.get("ticketId");
    const status = searchParams.get("status") || "all";

    if (ticketId) {
      const responses = await sql`
        SELECT * FROM support_responses WHERE ticket_id = ${ticketId} ORDER BY created_at ASC
      `;
      return NextResponse.json({
        responses: responses.map((r: any) => ({
          id: r.id,
          message: r.message,
          createdAt: r.created_at instanceof Date ? r.created_at.toISOString() : r.created_at,
        })),
      });
    }

    const tickets = status === "all"
      ? await sql`
          SELECT t.*, f.name as family_name
          FROM support_tickets t
          LEFT JOIN families f ON f.id = t.family_id
          ORDER BY t.created_at DESC
        `
      : await sql`
          SELECT t.*, f.name as family_name
          FROM support_tickets t
          LEFT JOIN families f ON f.id = t.family_id
          WHERE t.status = ${status}
          ORDER BY t.created_at DESC
        `;

    return NextResponse.json({
      tickets: tickets.map((t: any) => ({
        id: t.id,
        email: t.email,
        subject: t.subject,
        description: t.description,
        status: t.status,
        priority: t.priority,
        createdAt: t.created_at instanceof Date ? t.created_at.toISOString() : t.created_at,
        familyName: t.family_name,
      })),
    });
  } catch (error) {
    console.error("Admin support error:", error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// Update ticket status
export async function PATCH(request: Request) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const body = await request.json();
    const { ticketId, status } = body;
    if (!ticketId) return NextResponse.json({ error: "ticketId required" }, { status: 400 });

    await sql`UPDATE support_tickets SET status = ${status}, updated_at = NOW() WHERE id = ${ticketId}`;
    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// Create ticket or admin response
export async function POST(request: Request) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const body = await request.json();

    // Admin reply to a ticket
    if (body.ticketId && body.message) {
      const { ticketId, message } = body;
      await sql`
        INSERT INTO support_responses (id, ticket_id, message, created_at)
        VALUES (${crypto.randomUUID()}, ${ticketId}, ${message}, NOW())
      `;
      await sql`
        UPDATE support_tickets SET status = 'in_progress', updated_at = NOW()
        WHERE id = ${ticketId} AND status = 'open'
      `;
      return NextResponse.json({ success: true });
    }

    // Create a new ticket
    const { familyId, userId, email, subject, description, priority } = body;
    if (!email || !subject) {
      return NextResponse.json({ error: "email and subject required" }, { status: 400 });
    }
    await sql`
      INSERT INTO support_tickets (id, family_id, user_id, email, subject, description, priority, created_at, updated_at)
      VALUES (${crypto.randomUUID()}, ${familyId || null}, ${userId || null}, ${email}, ${subject}, ${description || ""}, ${priority || "normal"}, NOW(), NOW())
    `;
    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}
