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

export async function GET(request: NextRequest) {
  const repositoryId = request.nextUrl.searchParams.get("repositoryId");
  if (!repositoryId) {
    return NextResponse.json({ error: "repositoryId required" }, { status: 400 });
  }
  const db = await getDb();
  const { rows } = await db.query(
    `SELECT id, repository_id, thread_id, title, created_at, updated_at
     FROM chat_sessions
     WHERE repository_id = $1
     ORDER BY updated_at DESC
     LIMIT 50`,
    [repositoryId]
  );
  return NextResponse.json(rows);
}

export async function POST(request: NextRequest) {
  const { repositoryId } = (await request.json()) as { repositoryId: string };
  if (!repositoryId) {
    return NextResponse.json({ error: "repositoryId required" }, { status: 400 });
  }
  const db = await getDb();
  const { rows: repos } = await db.query(
    "SELECT id FROM repositories WHERE id = $1",
    [repositoryId]
  );
  if (repos.length === 0) {
    return NextResponse.json({ error: "Repository not found" }, { status: 404 });
  }
  const threadId = randomUUID();
  const { rows } = await db.query(
    `INSERT INTO chat_sessions (repository_id, thread_id, title)
     VALUES ($1, $2, 'New Chat')
     RETURNING *`,
    [repositoryId, threadId]
  );
  return NextResponse.json(rows[0], { status: 201 });
}
