import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";

const ADMIN_EMAIL = "brendonurban@gmail.com";

function isAdmin(email: string | null | undefined): boolean {
  return email === ADMIN_EMAIL;
}

/** GET — return the current landing mode */
export async function GET() {
  const session = await auth();

  if (!session?.user?.email || !isAdmin(session.user.email)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  try {
    const config = await db.siteConfig.findUnique({
      where: { id: "singleton" },
    });

    return NextResponse.json({
      mode: config?.landingMode ?? "open",
    });
  } catch (err) {
    logger.error({ err, action: "admin_landing_mode_get" }, "Failed to read landing mode");
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}

/** PUT — update the landing mode (body: { mode: "open" | "exclusive" }) */
export async function PUT(req: NextRequest) {
  const session = await auth();

  if (!session?.user?.email || !isAdmin(session.user.email)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  try {
    const body = await req.json();
    const { mode } = body;

    if (mode !== "open" && mode !== "exclusive") {
      return NextResponse.json(
        { error: 'Invalid mode. Must be "open" or "exclusive".' },
        { status: 400 }
      );
    }

    const config = await db.siteConfig.upsert({
      where: { id: "singleton" },
      update: { landingMode: mode },
      create: { id: "singleton", landingMode: mode },
    });

    logger.info({ action: "admin_landing_mode_update", mode }, "Landing mode updated");

    return NextResponse.json({ mode: config.landingMode });
  } catch (err) {
    logger.error({ err, action: "admin_landing_mode_put" }, "Failed to update landing mode");
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
