import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
import { z } from "zod";
import prisma from "@/server/db/prisma";
import { parseJson } from "@/server/http/parse";
import { ok } from "@/server/http/response";
import { withErrorHandling } from "@/server/http/withErrorHandling";

export const GET = withErrorHandling(async (request: NextRequest) => {
  const token = await getToken({ req: request });
  const isAdmin = Boolean(token);

  const settings = await prisma.googleSettings.findFirst();
  const base = settings || { id: 0, recaptchaSiteKey: "", googleAnalyticsId: "" };

  // Public GET must NOT expose secret keys.
  if (!isAdmin) {
    return ok({
      id: (base as any).id ?? 0,
      recaptchaSiteKey: (base as any).recaptchaSiteKey ?? "",
      googleAnalyticsId: (base as any).googleAnalyticsId ?? "",
    });
  }

  return ok(
    settings || {
      id: 0,
      recaptchaSiteKey: "",
      recaptchaSecretKey: "",
      googleAnalyticsId: "",
    },
  );
});

const GoogleSettingsUpsertSchema = z.object({
  id: z.number().int().optional(),
  recaptchaSiteKey: z.string().optional().default(""),
  recaptchaSecretKey: z.string().optional().default(""),
  googleAnalyticsId: z.string().optional().default(""),
});

export const POST = withErrorHandling(async (request: Request) => {
  const data = await parseJson(request, GoogleSettingsUpsertSchema);

  // Use upsert with id=1 as the singleton pattern (similar to navbar, hero)
  const settings = await prisma.googleSettings.upsert({
    where: { id: 1 },
    update: {
      recaptchaSiteKey: data.recaptchaSiteKey,
      recaptchaSecretKey: data.recaptchaSecretKey,
      googleAnalyticsId: data.googleAnalyticsId,
    },
    create: {
      recaptchaSiteKey: data.recaptchaSiteKey,
      recaptchaSecretKey: data.recaptchaSecretKey,
      googleAnalyticsId: data.googleAnalyticsId,
    },
  });

  return ok(settings);
});
