import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";

export const dynamic = "force-dynamic";

async function resolveAdminMembership(userId: string, orgId: string) {
  const membership = await prisma.orgMembership.findUnique({
    where: { userId_orgId: { userId, orgId } },
    select: { role: true },
  });
  return membership ?? null;
}

/** GET /api/white-label?orgId=<activeOrgId> -- fetch the org's WhiteLabelConfig.
 *
 *  orgId must be the caller's active org (sent by the client via useBrand().orgId).
 *  It is authorized server-side: the caller must have owner|admin membership for
 *  that org. No fallback to "first membership" -- if orgId is missing, return 400.
 */
export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const orgId = new URL(req.url).searchParams.get("orgId");
  if (!orgId) return NextResponse.json({ error: "orgId is required" }, { status: 400 });

  const membership = await resolveAdminMembership(user.id, orgId);
  if (!membership || !["owner", "admin"].includes(membership.role)) {
    return NextResponse.json({ error: "Org admin access required" }, { status: 403 });
  }

  const config = await prisma.whiteLabelConfig.findUnique({
    where: { organizationId: orgId },
  });

  return NextResponse.json({ config: config ?? null });
}

/** PUT /api/white-label -- upsert the org's WhiteLabelConfig.
 *
 *  Body must include orgId (the caller's active org from useBrand().orgId).
 *  Authorization is checked server-side; orgId is never written to the config row.
 */
export async function PUT(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  let body: Record<string, unknown>;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }

  const orgId = typeof body.orgId === "string" && body.orgId.trim() ? body.orgId.trim() : null;
  if (!orgId) return NextResponse.json({ error: "orgId is required" }, { status: 400 });

  const membership = await resolveAdminMembership(user.id, orgId);
  if (!membership || !["owner", "admin"].includes(membership.role)) {
    return NextResponse.json({ error: "Org admin access required" }, { status: 403 });
  }

  // Extract only the known WhiteLabelConfig fields. orgId comes from above (auth-derived),
  // never from body, so a client cannot cross-write another org's config.
  const {
    enabled,
    agencyName,
    logoUrl,
    logoDarkUrl,
    faviconUrl,
    primaryColor,
    secondaryColor,
    accentColor,
    fontFamily,
    supportEmail,
    removeMeseoBranding,
  } = body as {
    enabled?: boolean;
    agencyName?: string | null;
    logoUrl?: string | null;
    logoDarkUrl?: string | null;
    faviconUrl?: string | null;
    primaryColor?: string | null;
    secondaryColor?: string | null;
    accentColor?: string | null;
    fontFamily?: string | null;
    supportEmail?: string | null;
    removeMeseoBranding?: boolean;
  };

  const data = {
    ...(enabled !== undefined && { enabled }),
    ...(agencyName !== undefined && { agencyName }),
    ...(logoUrl !== undefined && { logoUrl }),
    ...(logoDarkUrl !== undefined && { logoDarkUrl }),
    ...(faviconUrl !== undefined && { faviconUrl }),
    ...(primaryColor !== undefined && { primaryColor }),
    ...(secondaryColor !== undefined && { secondaryColor }),
    ...(accentColor !== undefined && { accentColor }),
    ...(fontFamily !== undefined && { fontFamily }),
    ...(supportEmail !== undefined && { supportEmail }),
    ...(removeMeseoBranding !== undefined && { removeMeseoBranding }),
  };

  const config = await prisma.whiteLabelConfig.upsert({
    where: { organizationId: orgId },
    update: data,
    create: { ...data, organizationId: orgId },
  });

  return NextResponse.json({ config });
}
