import { NextResponse } from 'next/server';
import { getAdminDb } from '@/lib/firebase/admin';

type StoredMessageRole = 'user' | 'assistant';

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

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 },
      );
    }

    const adminDb = getAdminDb();
    const docRef = adminDb.collection('chat_conversations').doc(projectId);
    const snapshot = await docRef.get();

    if (!snapshot.exists) {
      const empty: ConversationResponse = { messages: [] };
      return NextResponse.json(empty);
    }

    const data = snapshot.data() as { messages?: ConversationMessage[] };
    const messages = Array.isArray(data.messages) ? data.messages : [];

    const response: ConversationResponse = { messages };
    return NextResponse.json(response);
  } catch (error) {
    console.error('[ai/conversation] Failed to load conversation', error);
    return NextResponse.json(
      {
        error: 'Failed to load conversation',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 },
    );
  }
}


