import { getAdSettings, upsertAdSettings, type AdPlacement } from "@/lib/ads/settings"
import { AdSettingsForm } from "@/components/admin/ad-settings-form"
import { revalidatePath } from "next/cache"

export const dynamic = "force-dynamic"

// Server action that the <AdSettingsForm/> submits to. Keeping it here
// (colocated with the page that owns it) means the form stays a simple
// controlled component and we avoid shipping a separate API route just
// for the admin upsert. Auth is already enforced by the shared
// /admin/layout.tsx guard.
async function saveAdSettings(formData: FormData) {
  "use server"

  const enabled = formData.get("enabled") === "on"
  const frequency = Number(formData.get("frequency") ?? 3)
  const placement = String(formData.get("placement") ?? "interstitial") as AdPlacement
  const rawScript = String(formData.get("script") ?? "").trim()
  const rawLabel = String(formData.get("label") ?? "").trim()

  await upsertAdSettings({
    enabled,
    frequency: Number.isFinite(frequency) ? frequency : 3,
    placement,
    script: rawScript.length === 0 ? null : rawScript,
    label: rawLabel.length === 0 ? null : rawLabel,
  })

  // Refresh both this page and the public config endpoint's cached view.
  revalidatePath("/admin/ads")
  revalidatePath("/api/ads/config")
}

export default async function AdminAdsPage() {
  const settings = await getAdSettings()
  return (
    <div className="space-y-6">
      <div className="space-y-1">
        <h2 className="text-lg font-semibold tracking-tight md:text-xl">Ads (Adsterra)</h2>
        <p className="max-w-2xl text-sm text-muted-foreground">
          Paste your Adsterra ad script below. Pick how many completed video chats
          should pass between each impression. Ads are shown in a dismissable
          modal after the user ends / skips a chat.
        </p>
      </div>
      <AdSettingsForm action={saveAdSettings} initial={settings} />
    </div>
  )
}
