import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession, hasPermission } from "@/lib/adminAuth";
import { getSettings } from "@/lib/settings";
import { updateSeoSettingsAction } from "@/lib/actions/seo";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

export async function OPTIONS(request: NextRequest) {
  return corsPreflight(request);
}

export async function GET(request: NextRequest) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  if (!(await hasPermission("seo"))) {
    return NextResponse.json({ error: "Keine Berechtigung." }, { status: 403, headers });
  }
  const settings = await getSettings();
  return NextResponse.json({ seoSettings: settings.seoSettings }, { headers });
}

// "indexable" ist die einzige wirklich heikle Einstellung hier (trägt die
// ganze Seite aus Google aus) — der Renderer verlangt dafür vorher eine
// erfolgreiche /verify-password-Bestätigung. Restliche Felder (Meta-
// Beschreibung, Keywords, Verifizierungscodes) sind unkritisch.
export async function POST(request: NextRequest) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const body = await request.json().catch(() => null);
  const formData = new FormData();
  formData.set("defaultMetaDescription", typeof body?.defaultMetaDescription === "string" ? body.defaultMetaDescription : "");
  formData.set("defaultMetaDescriptionEn", typeof body?.defaultMetaDescriptionEn === "string" ? body.defaultMetaDescriptionEn : "");
  formData.set("keywords", typeof body?.keywords === "string" ? body.keywords : "");
  formData.set("keywordsEn", typeof body?.keywordsEn === "string" ? body.keywordsEn : "");
  formData.set("googleSiteVerification", typeof body?.googleSiteVerification === "string" ? body.googleSiteVerification : "");
  formData.set("bingSiteVerification", typeof body?.bingSiteVerification === "string" ? body.bingSiteVerification : "");
  formData.set("googleAnalyticsId", typeof body?.googleAnalyticsId === "string" ? body.googleAnalyticsId : "");
  formData.set("businessPhone", typeof body?.businessPhone === "string" ? body.businessPhone : "");
  formData.set("priceRange", typeof body?.priceRange === "string" ? body.priceRange : "");
  if (body?.indexable) formData.set("indexable", "on");

  const result = await updateSeoSettingsAction({}, formData);
  if (result.error) return NextResponse.json({ error: result.error }, { status: 400, headers });
  return NextResponse.json({ ok: true }, { headers });
}
