import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireFamily, requireOwnership } from "@/lib/auth";

// GET - list chat sessions for a child
export async function GET(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const { searchParams } = new URL(request.url);
  const childId = searchParams.get("childId") || "default";

  try {
    // Fetch sessions only (messages fetched separately for better control)
    const sessions = await sql`
      SELECT id, title, created_at as "createdAt", updated_at as "updatedAt"
      FROM chat_sessions
      WHERE child_id = ${childId}
      ORDER BY updated_at DESC
    `;

    // Fetch messages for all sessions in one go (if any)
    const messages = await sql`
      SELECT session_id, id, role, content, created_at as "createdAt"
      FROM chat_messages
      ORDER BY created_at
    `;

    // Merge messages into sessions
    const msgMap = new Map();
    (messages || []).forEach((m: any) => {
      if (!msgMap.has(m.session_id)) msgMap.set(m.session_id, []);
      msgMap.get(m.session_id).push(m);
    });

    const sessionsWithMessages = (sessions || []).map((s: any) => ({
      ...s,
      messages: msgMap.get(s.id) || [],
    }));

    return NextResponse.json({ sessions: sessionsWithMessages });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// POST - create new chat session
export async function POST(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const body = await request.json();
    const { childId, title } = body;

    if (!childId) {
      return NextResponse.json({ error: "childId required" }, { status: 400 });
    }

    // Verify ownership
    const ownership = await requireOwnership(childId, "children", "Child");
    if (!ownership.success) {
      return NextResponse.json({ error: ownership.error }, { status: ownership.status });
    }

    const [session] = await sql`
      INSERT INTO chat_sessions (child_id, title)
      VALUES (${childId}, ${title || "New conversation"})
      RETURNING id, title, created_at as "createdAt", updated_at as "updatedAt"
    `;

    return NextResponse.json({ success: true, session });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// PATCH - update session title or add message
export async function PATCH(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const body = await request.json();
    const { sessionId, title, role, content } = body;

    if (!sessionId) {
      return NextResponse.json({ error: "sessionId required" }, { status: 400 });
    }

    if (title) {
      await sql`UPDATE chat_sessions SET title = ${title}, updated_at = NOW() WHERE id = ${sessionId}`;
    }

    if (role && content) {
      await sql`INSERT INTO chat_messages (session_id, role, content) VALUES (${sessionId}, ${role}, ${content})`;
      await sql`UPDATE chat_sessions SET updated_at = NOW() WHERE id = ${sessionId}`;
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// DELETE - delete chat session
export async function DELETE(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const { searchParams } = new URL(request.url);
  const id = searchParams.get("id");

  if (!id) {
    return NextResponse.json({ error: "ID required" }, { status: 400 });
  }

  // Verify ownership via child_id
  const sessions = await sql`SELECT child_id FROM chat_sessions WHERE id = ${id}`;
  if (!sessions.length) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
  const ownership = await requireOwnership(sessions[0].child_id, "children", "Child");
  if (!ownership.success) {
    return NextResponse.json({ error: ownership.error }, { status: ownership.status });
  }

  try {
    await sql`DELETE FROM chat_sessions WHERE id = ${id}`;
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}