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

async function verifyOwnership(projectId: string, email: string): Promise<boolean> {
  const rows = await query<{ id: string }>(
    `SELECT p.id 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]
  );
  return rows.length > 0;
}

/**
 * GET — returns surfaces[] and surfaceThemes{} for the project.
 */
export async function GET(
  _req: Request,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const session = await getServerSession(authOptions);
    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 AND u.data->>'email' = $2
       LIMIT 1`,
      [projectId, session.user.email]
    );

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

    const data = rows[0].data ?? {};
    return NextResponse.json({
      surfaces: (data.surfaces ?? []) as string[],
      surfaceThemes: (data.surfaceThemes ?? {}) as Record<string, string>,
    });
  } catch (err) {
    console.error('[design-surfaces GET]', err);
    return NextResponse.json({ error: 'Internal error' }, { status: 500 });
  }
}

/**
 * PATCH — two operations:
 *   { surfaces: string[] }              — save the active surface list
 *   { surface: string, theme: string }  — lock in a theme for one surface
 */
export async function PATCH(
  req: Request,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const owned = await verifyOwnership(projectId, session.user.email);
    if (!owned) return NextResponse.json({ error: 'Project not found' }, { status: 404 });

    const body = await req.json() as
      | { surfaces: string[] }
      | { surface: string; theme: string };

    if ('surfaces' in body) {
      await query(
        `UPDATE fs_projects
         SET data = data || jsonb_build_object('surfaces', $2::jsonb),
             updated_at = NOW()
         WHERE id = $1`,
        [projectId, JSON.stringify(body.surfaces)]
      );
    } else if ('surface' in body && 'theme' in body) {
      await query(
        `UPDATE fs_projects
         SET data = data || jsonb_build_object(
           'surfaceThemes',
           COALESCE(data->'surfaceThemes', '{}'::jsonb) || jsonb_build_object($2, $3)
         ),
         updated_at = NOW()
         WHERE id = $1`,
        [projectId, body.surface, body.theme]
      );
    } else {
      return NextResponse.json({ error: 'Invalid body' }, { status: 400 });
    }

    return NextResponse.json({ success: true });
  } catch (err) {
    console.error('[design-surfaces PATCH]', err);
    return NextResponse.json({ error: 'Internal error' }, { status: 500 });
  }
}
