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

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const session = await authSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const rows = await query<{ data: Record<string, unknown> }>(
      `SELECT p.data FROM fs_projects p
       JOIN fs_users u ON u.id = p.user_id
       WHERE p.id = $1::text AND u.data->>'email' = $2::text LIMIT 1`,
      [projectId, session.user.email]
    );

    if (rows.length === 0) {
      return NextResponse.json({ error: 'Project not found' }, { status: 404 });
    }

    const data = rows[0].data ?? {};
    const stage = (data.analysisStage as string) ?? 'cloning';
    const analysisResult = stage === 'done' ? data.analysisResult : undefined;

    return NextResponse.json({ stage, analysisResult });
  } catch (err) {
    console.error('[analysis-status]', err);
    return NextResponse.json({ error: 'Internal error' }, { status: 500 });
  }
}
