import { NextRequest, NextResponse } from "next/server";
import { getDb } from "@/lib/db";

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const db = await getDb();
  const { rows } = await db.query("SELECT * FROM chat_sessions WHERE id = $1", [id]);
  if (rows.length === 0) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
  return NextResponse.json(rows[0]);
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const body = await request.json();
  const { title, messages, agui_history, analysis_state, pending_interrupt } = body as {
    title?: string;
    messages?: unknown;
    agui_history?: unknown;
    analysis_state?: unknown;
    pending_interrupt?: unknown;
  };

  const db = await getDb();
  const sets: string[] = ["updated_at = NOW()"];
  const vals: unknown[] = [];
  let idx = 1;

  if (title !== undefined) { sets.push(`title = $${idx}`); vals.push(title); idx++; }
  if (messages !== undefined) { sets.push(`messages = $${idx}`); vals.push(JSON.stringify(messages)); idx++; }
  if (agui_history !== undefined) { sets.push(`agui_history = $${idx}`); vals.push(JSON.stringify(agui_history)); idx++; }
  if (analysis_state !== undefined) { sets.push(`analysis_state = $${idx}`); vals.push(JSON.stringify(analysis_state)); idx++; }
  if (pending_interrupt !== undefined) { sets.push(`pending_interrupt = $${idx}`); vals.push(JSON.stringify(pending_interrupt)); idx++; }

  vals.push(id);
  const { rows } = await db.query(
    `UPDATE chat_sessions SET ${sets.join(", ")} WHERE id = $${idx} RETURNING *`,
    vals
  );
  if (rows.length === 0) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
  return NextResponse.json(rows[0]);
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const db = await getDb();
  await db.query("DELETE FROM chat_sessions WHERE id = $1", [id]);
  return NextResponse.json({ ok: true });
}
