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<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;

    // 1. Authenticate the Workspace API key or Browser Session
    const principal = await requireWorkspacePrincipal(request);
    if (principal instanceof NextResponse) return principal;

    // 2. Fetch user email from principal.userId
    const userRow = await queryOne<{ data: any }>(
      `SELECT data FROM fs_users WHERE id = $1 LIMIT 1`,
      [principal.userId]
    );
    const email = userRow?.data?.email;
    if (!email) {
      return NextResponse.json({ error: 'User email not found' }, { status: 404 });
    }

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

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

    return NextResponse.json({ success: true, project: { id: rows[0].id, ...rows[0].data } });
  } catch (error) {
    console.error('[GET /api/projects/:id] Error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch project', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

export async function PATCH(
  request: Request,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const body = await request.json();

    // 1. Authenticate the Workspace API key or Browser Session
    const principal = await requireWorkspacePrincipal(request);
    if (principal instanceof NextResponse) return principal;

    // 2. Fetch user email from principal.userId
    const userRow = await queryOne<{ data: any }>(
      `SELECT data FROM fs_users WHERE id = $1 LIMIT 1`,
      [principal.userId]
    );
    const email = userRow?.data?.email;
    if (!email) {
      return NextResponse.json({ error: 'User email not found' }, { status: 404 });
    }

    // Fetch current data (verify ownership)
    const rows = await query<{ id: string; data: any }>(`
      SELECT p.id, p.data
      FROM fs_projects p
      JOIN fs_users u ON u.id = p.user_id
      WHERE p.id = $1 AND u.data->>'email' = $2
      LIMIT 1
    `, [projectId, email]);

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

    const current = rows[0].data || {};
    const updated = { ...current };
    const allowedFields = ['vision', 'description', 'name', 'githubRepo', 'productVision', 'productName'];
    for (const field of allowedFields) {
      if (body[field] !== undefined) updated[field] = body[field];
    }
    updated.updatedAt = new Date().toISOString();

    await query(`
      UPDATE fs_projects SET data = $1::jsonb WHERE id = $2
    `, [JSON.stringify(updated), projectId]);

    return NextResponse.json({ success: true, message: 'Project updated successfully' });
  } catch (error) {
    console.error('[PATCH /api/projects/:id] Error:', error);
    return NextResponse.json(
      { error: 'Failed to update project', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}
