import { NextResponse } from 'next/server';
import { query } from '@/lib/db-postgres';

const ENSURE_TABLE = `
  CREATE TABLE IF NOT EXISTS chat_conversations (
    project_id text PRIMARY KEY,
    messages    jsonb NOT NULL DEFAULT '[]',
    updated_at  timestamptz NOT NULL DEFAULT NOW()
  )
`;

type StoredMessageRole = 'user' | 'assistant';

type ConversationMessage = {
  role: StoredMessageRole;
  content: string;
  createdAt?: string;
};

type ConversationResponse = {
  messages: ConversationMessage[];
};

export async function GET(request: Request) {
  try {
    const url = new URL(request.url);
    const projectId = (url.searchParams.get('projectId') ?? '').trim();

    if (!projectId) {
      return NextResponse.json({ error: 'projectId is required' }, { status: 400 });
    }

    await query(ENSURE_TABLE);

    const rows = await query<{ messages: ConversationMessage[] }>(
      `SELECT messages FROM chat_conversations WHERE project_id = $1`,
      [projectId]
    );

    const messages: ConversationMessage[] = rows[0]?.messages ?? [];
    const response: ConversationResponse = { messages };
    return NextResponse.json(response);
  } catch (error) {
    console.error('[GET /api/ai/conversation] Error:', error);
    return NextResponse.json({ messages: [] });
  }
}

export async function DELETE(request: Request) {
  try {
    const url = new URL(request.url);
    const projectId = (url.searchParams.get('projectId') ?? '').trim();

    if (!projectId) {
      return NextResponse.json({ error: 'projectId is required' }, { status: 400 });
    }

    await query(ENSURE_TABLE);
    await query(
      `DELETE FROM chat_conversations WHERE project_id = $1`,
      [projectId]
    );

    return NextResponse.json({ ok: true });
  } catch (error) {
    console.error('[DELETE /api/ai/conversation] Error:', error);
    return NextResponse.json({ error: 'Failed to reset conversation' }, { status: 500 });
  }
}
