import "server-only"

import {
  getSystemSetting,
  upsertSystemSetting,
} from "@/modules/settings/data-access-system-settings"
import { DEFAULT_BRAND_CONFIG, type BrandConfig } from "@/modules/settings/brand-config"

export type { BrandConfig }
export { DEFAULT_BRAND_CONFIG }

/** 品牌配置键名 */
const BRAND_KEYS = {
  schoolName: "schoolName",
  logoUrl: "logoUrl",
  testimonialQuote: "testimonialQuote",
  testimonialAuthor: "testimonialAuthor",
} as const

/**
 * 获取品牌配置（audit-P2-6 新增）
 *
 * 从 system_settings 表 brand 分类读取，未配置项使用默认值。
 */
export async function getBrandConfig(): Promise<BrandConfig> {
  const [schoolNameRow, logoUrlRow, quoteRow, authorRow] = await Promise.all([
    getSystemSetting("brand", BRAND_KEYS.schoolName),
    getSystemSetting("brand", BRAND_KEYS.logoUrl),
    getSystemSetting("brand", BRAND_KEYS.testimonialQuote),
    getSystemSetting("brand", BRAND_KEYS.testimonialAuthor),
  ])

  return {
    schoolName: schoolNameRow?.value || DEFAULT_BRAND_CONFIG.schoolName,
    logoUrl: logoUrlRow?.value || null,
    testimonialQuote: quoteRow?.value || DEFAULT_BRAND_CONFIG.testimonialQuote,
    testimonialAuthor: authorRow?.value || DEFAULT_BRAND_CONFIG.testimonialAuthor,
  }
}

/**
 * 保存品牌配置（audit-P2-6 新增）
 */
export async function saveBrandConfig(
  config: BrandConfig,
  updatedBy?: string,
): Promise<void> {
  await Promise.all([
    upsertSystemSetting({
      category: "brand",
      key: BRAND_KEYS.schoolName,
      value: config.schoolName,
      valueType: "string",
      updatedBy,
    }),
    upsertSystemSetting({
      category: "brand",
      key: BRAND_KEYS.logoUrl,
      value: config.logoUrl ?? "",
      valueType: "string",
      updatedBy,
    }),
    upsertSystemSetting({
      category: "brand",
      key: BRAND_KEYS.testimonialQuote,
      value: config.testimonialQuote,
      valueType: "string",
      updatedBy,
    }),
    upsertSystemSetting({
      category: "brand",
      key: BRAND_KEYS.testimonialAuthor,
      value: config.testimonialAuthor,
      valueType: "string",
      updatedBy,
    }),
  ])
}
