import { NextResponse } from "next/server";
import { authSession } from "@/lib/auth/session-server";
import { query } from "@/lib/db-postgres";
import type { DesignKitOverrides, DesignKitPersisted } from "@/lib/design-kits/types";
import { DEFAULT_DESIGN_KIT_ID } from "@/lib/design-kits/types";
import { getStarterKit } from "@/lib/design-kits/registry";

function emptyPersisted(): DesignKitPersisted {
  return { kitId: DEFAULT_DESIGN_KIT_ID, perKit: {} };
}

/**
 * GET — active starter kit + merged overrides for that kit (+ registry list).
 */
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 raw = data.designKit as DesignKitPersisted | undefined;
    const persisted = raw && typeof raw === "object" ? raw : emptyPersisted();
    const kitId =
      typeof persisted.kitId === "string" && getStarterKit(persisted.kitId)
        ? persisted.kitId
        : DEFAULT_DESIGN_KIT_ID;
    const perKit =
      persisted.perKit && typeof persisted.perKit === "object"
        ? (persisted.perKit as Record<string, DesignKitOverrides>)
        : {};

    return NextResponse.json({
      kitId,
      overrides: perKit[kitId] ?? {},
      perKit,
    });
  } catch (err) {
    console.error("[design-kit GET]", err);
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}

/**
 * PATCH — switch starter kit and/or merge overrides for the active (or given) kit.
 *
 * Body:
 *   { kitId?: string }
 *   { overrides?: Partial<DesignKitOverrides> }
 *   { kitId, overrides? } — switch kit then optionally seed overrides
 */
export async function PATCH(
  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 current = rows[0].data ?? {};
    const raw = current.designKit as DesignKitPersisted | undefined;
    let dk: DesignKitPersisted =
      raw && typeof raw === "object"
        ? {
            kitId: typeof raw.kitId === "string" ? raw.kitId : DEFAULT_DESIGN_KIT_ID,
            perKit:
              raw.perKit && typeof raw.perKit === "object"
                ? { ...(raw.perKit as Record<string, DesignKitOverrides>) }
                : {},
          }
        : emptyPersisted();

    const body = (await req.json()) as {
      kitId?: string;
      overrides?: Partial<DesignKitOverrides>;
    };

    if (body.kitId !== undefined) {
      if (!getStarterKit(body.kitId)) {
        return NextResponse.json({ error: "Unknown kit id" }, { status: 400 });
      }
      dk.kitId = body.kitId;
    }

    const targetKit = dk.kitId;

    if (body.overrides && typeof body.overrides === "object") {
      const prev = dk.perKit[targetKit] ?? {};
      dk.perKit = {
        ...dk.perKit,
        [targetKit]: { ...prev, ...body.overrides },
      };
    }

    const updated = {
      ...current,
      designKit: dk,
      updatedAt: new Date().toISOString(),
    };

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

    return NextResponse.json({
      success: true,
      kitId: dk.kitId,
      overrides: dk.perKit[dk.kitId] ?? {},
      perKit: dk.perKit,
    });
  } catch (err) {
    console.error("[design-kit PATCH]", err);
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}
