import { NextRequest } from "next/server";
import { db } from "@/lib/db";
import { requireAdminSession, unauthorized, ok, fail } from "@/lib/admin-api";

// GET - return singleton site settings (upsert defaults if missing)
export async function GET() {
  const session = await requireAdminSession();
  if (!session) return unauthorized();

  try {
    const settings = await db.siteSetting.upsert({
      where: { id: "singleton" },
      update: {},
      create: { id: "singleton" },
    });
    return ok({ settings });
  } catch (e) {
    console.error(e);
    return fail("Failed to load settings", 500);
  }
}

// PUT - update singleton site settings
export async function PUT(req: NextRequest) {
  const session = await requireAdminSession();
  if (!session) return unauthorized();

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

    const data = {
      companyName: body.companyName ?? undefined,
      shortName: body.shortName ?? undefined,
      tagline: body.tagline ?? undefined,
      logo: body.logo ?? undefined,
      favicon: body.favicon ?? undefined,
      phone: body.phone ?? undefined,
      whatsapp: body.whatsapp ?? undefined,
      email: body.email ?? undefined,
      address: body.address ?? undefined,
      mapEmbed: body.mapEmbed ?? undefined,
      workingHours: body.workingHours ?? undefined,
      ntn: body.ntn ?? undefined,
      footerText: body.footerText ?? undefined,
      copyright: body.copyright ?? undefined,
      facebook: body.facebook ?? undefined,
      instagram: body.instagram ?? undefined,
      linkedin: body.linkedin ?? undefined,
      youtube: body.youtube ?? undefined,
      twitter: body.twitter ?? undefined,
      defaultMetaTitle: body.defaultMetaTitle ?? undefined,
      defaultMetaDescription: body.defaultMetaDescription ?? undefined,
    };

    // Strip undefined fields so we don't overwrite existing values with nulls
    Object.keys(data).forEach((k) => {
      if ((data as any)[k] === undefined) delete (data as any)[k];
    });

    const settings = await db.siteSetting.upsert({
      where: { id: "singleton" },
      update: data,
      create: { id: "singleton", ...data },
    });

    return ok({ settings });
  } catch (e) {
    console.error(e);
    return fail("Failed to save settings", 500);
  }
}
