"use server"

import { redirect } from "next/navigation"
import { revalidatePath } from "next/cache"
import { eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { profiles } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { PLAN_LIMITS } from "@/lib/stripe/plans"
import { normalizeHexColor } from "@/lib/branding"
import type { Plan } from "@/types"

/**
 * Saves the current user's white-label branding (brand name, logo, accent color,
 * "Powered by" toggle). Only landlord/lifetime plans may edit branding — everyone
 * else is redirected to billing. Values are validated before persisting.
 */
export async function updateBranding(formData: FormData) {
  const user = await getSessionUser()
  if (!user) redirect("/login")

  // Plan gate: white-label is landlord/lifetime only.
  const profile = await db.query.profiles.findFirst({
    where: eq(profiles.id, user.id),
    columns: { plan: true },
  })
  const plan = (profile?.plan ?? "starter") as Plan
  if (!PLAN_LIMITS[plan]?.hasWhiteLabel) {
    redirect("/settings/billing")
  }

  // ── Validate inputs ──────────────────────────────────────────────────────
  const rawName = (formData.get("brand_name") as string | null)?.trim() ?? ""
  const brandName = rawName ? rawName.slice(0, 60) : null

  const rawLogo = (formData.get("brand_logo_url") as string | null)?.trim() ?? ""
  // Only accept logo URLs served by our own gated files route.
  const brandLogoUrl = rawLogo && rawLogo.startsWith("/api/files/") ? rawLogo : null

  const rawColor = (formData.get("brand_color") as string | null) ?? ""
  const brandColor = normalizeHexColor(rawColor)
  // If a color was supplied but is malformed, reject rather than silently drop it.
  if (rawColor.trim() && !brandColor) {
    throw new Error("Accent color must be a hex value like #4f46e5")
  }

  const hidePoweredBy = formData.get("hide_powered_by") === "on"

  await db
    .update(profiles)
    .set({
      brand_name: brandName,
      brand_logo_url: brandLogoUrl,
      brand_color: brandColor,
      hide_powered_by: hidePoweredBy,
    })
    .where(eq(profiles.id, user.id))

  revalidatePath("/settings/branding")
}
