/**
 * GET    /api/chat/threads/[id]  — load a thread + its messages
 * PATCH  /api/chat/threads/[id]  — rename a thread
 * DELETE /api/chat/threads/[id]  — delete a thread
 */
import { NextResponse } from 'next/server';
import { requireWorkspacePrincipal } from '@/lib/auth/workspace-auth';
import { query, queryOne } from '@/lib/db-postgres';

export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const principal = await requireWorkspacePrincipal(request);
  if (principal instanceof NextResponse) return principal;

  const userRow = await queryOne<{ data: { email?: string } }>(
    `SELECT data FROM fs_users WHERE id = $1 LIMIT 1`,
    [principal.userId]
  );
  if (!userRow?.data?.email) return NextResponse.json({ error: 'Unauthorized user' }, { status: 401 });
  const sessionEmail = userRow.data.email;

  const { id } = await params;

  const threads = await query<any>(
    `SELECT id, data, created_at, updated_at FROM fs_chat_threads WHERE id = $1 AND user_id = $2`,
    [id, sessionEmail],
  );
  if (!threads.length) return NextResponse.json({ error: 'Not found' }, { status: 404 });

  const messages = await query<any>(
    `SELECT id, data, created_at FROM fs_chat_messages WHERE thread_id = $1 ORDER BY created_at ASC`,
    [id],
  );

  const t = threads[0];
  return NextResponse.json({
    thread: { id: t.id, title: t.data?.title || 'New conversation', createdAt: t.created_at, updatedAt: t.updated_at },
    messages: messages.map((m: any) => ({ id: m.id, ...m.data, createdAt: m.created_at })),
  });
}

export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const principal = await requireWorkspacePrincipal(request);
  if (principal instanceof NextResponse) return principal;

  const userRow = await queryOne<{ data: { email?: string } }>(
    `SELECT data FROM fs_users WHERE id = $1 LIMIT 1`,
    [principal.userId]
  );
  if (!userRow?.data?.email) return NextResponse.json({ error: 'Unauthorized user' }, { status: 401 });
  const sessionEmail = userRow.data.email;

  const { id } = await params;
  const { title } = await request.json().catch(() => ({}));
  if (!title) return NextResponse.json({ error: 'title required' }, { status: 400 });

  await query(
    `UPDATE fs_chat_threads SET data = data || $3, updated_at = NOW() WHERE id = $1 AND user_id = $2`,
    [id, sessionEmail, JSON.stringify({ title })],
  );
  return NextResponse.json({ ok: true });
}

export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const principal = await requireWorkspacePrincipal(request);
  if (principal instanceof NextResponse) return principal;

  const userRow = await queryOne<{ data: { email?: string } }>(
    `SELECT data FROM fs_users WHERE id = $1 LIMIT 1`,
    [principal.userId]
  );
  if (!userRow?.data?.email) return NextResponse.json({ error: 'Unauthorized user' }, { status: 401 });
  const sessionEmail = userRow.data.email;

  const { id } = await params;
  await query(`DELETE FROM fs_chat_threads WHERE id = $1 AND user_id = $2`, [id, sessionEmail]);
  return NextResponse.json({ ok: true });
}
