"use server"

import { z } from "zod"
import { revalidatePath } from "next/cache"

import type { ActionState } from "@/shared/types/action-state"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getSession } from "@/shared/lib/session"

import { getBrandConfig, saveBrandConfig } from "./data-access-brand"
import type { BrandConfig } from "./brand-config"

const BrandConfigSchema = z.object({
  schoolName: z.string().min(1).max(255),
  logoUrl: z.string().url().or(z.literal("")).default(""),
  testimonialQuote: z.string().min(1).max(500),
  testimonialAuthor: z.string().min(1).max(100),
})

/**
 * 获取品牌配置 Server Action（audit-P2-6 新增）
 */
export async function getBrandConfigAction(): Promise<ActionState<BrandConfig>> {
  try {
    await requirePermission(Permissions.SCHOOL_MANAGE)
    const config = await getBrandConfig()
    return { success: true, data: config }
  } catch (e) {
    return {
      success: false,
      message: e instanceof Error ? e.message : "Failed to get brand config",
    }
  }
}

/**
 * 保存品牌配置 Server Action（audit-P2-6 新增）
 */
export async function saveBrandConfigAction(
  prevState: ActionState<BrandConfig>,
  formData: FormData,
): Promise<ActionState<BrandConfig>> {
  try {
    await requirePermission(Permissions.SCHOOL_MANAGE)
    const session = await getSession()

    const parsed = BrandConfigSchema.safeParse({
      schoolName: formData.get("schoolName"),
      logoUrl: formData.get("logoUrl"),
      testimonialQuote: formData.get("testimonialQuote"),
      testimonialAuthor: formData.get("testimonialAuthor"),
    })

    if (!parsed.success) {
      return {
        success: false,
        message: parsed.error.issues[0]?.message ?? "Invalid brand config",
      }
    }

    const config: BrandConfig = {
      schoolName: parsed.data.schoolName,
      logoUrl: parsed.data.logoUrl || null,
      testimonialQuote: parsed.data.testimonialQuote,
      testimonialAuthor: parsed.data.testimonialAuthor,
    }

    await saveBrandConfig(config, session?.user?.id)
    revalidatePath("/admin/settings")
    revalidatePath("/(auth)/login")
    revalidatePath("/(auth)/register")

    return { success: true, data: config, message: "Brand configuration saved" }
  } catch (e) {
    return {
      success: false,
      message: e instanceof Error ? e.message : "Failed to save brand config",
    }
  }
}
