import "server-only"

import { and, eq } from "drizzle-orm"

import { db } from "@/shared/db"
import { systemSettings } from "@/shared/db/schema"

// --- System Settings operations ---

/**
 * 系统设置分类
 */
export type SystemSettingCategory =
  | "school_info"
  | "security_policy"
  | "file_upload"
  | "notification_config"
  | "audit_retention"
  | "brand"

/**
 * 系统设置值类型
 */
export type SystemSettingValueType = "string" | "number" | "boolean" | "json"

/**
 * 系统设置记录（数据库行）
 *
 * 注意：`category` 和 `valueType` 在数据库中存储为 varchar，读取时为 `string`。
 * 写入时通过 `SystemSettingCategory` / `SystemSettingValueType` 联合类型约束输入。
 */
export interface SystemSettingRecord {
  id: string
  category: string
  key: string
  value: string
  valueType: string
  updatedBy: string | null
  updatedAt: Date
}

/**
 * 获取指定分类下所有设置项
 */
export async function getSystemSettingsByCategory(
  category: SystemSettingCategory
): Promise<SystemSettingRecord[]> {
  const rows = await db
    .select()
    .from(systemSettings)
    .where(eq(systemSettings.category, category))
  return rows
}

/**
 * 获取所有系统设置项
 */
export async function getAllSystemSettings(): Promise<SystemSettingRecord[]> {
  const rows = await db.select().from(systemSettings)
  return rows
}

/**
 * 获取单个设置项
 */
export async function getSystemSetting(
  category: SystemSettingCategory,
  key: string
): Promise<SystemSettingRecord | null> {
  const [row] = await db
    .select()
    .from(systemSettings)
    .where(and(eq(systemSettings.category, category), eq(systemSettings.key, key)))
    .limit(1)
  return row ?? null
}

/**
 * 插入或更新设置项（upsert）
 */
export async function upsertSystemSetting(
  params: {
    category: SystemSettingCategory
    key: string
    value: string
    valueType: SystemSettingValueType
    updatedBy?: string
  }
): Promise<void> {
  const { category, key, value, valueType, updatedBy } = params
  const existing = await getSystemSetting(category, key)

  if (existing) {
    await db
      .update(systemSettings)
      .set({ value, valueType, updatedBy: updatedBy ?? null, updatedAt: new Date() })
      .where(eq(systemSettings.id, existing.id))
  } else {
    await db.insert(systemSettings).values({
      category,
      key,
      value,
      valueType,
      updatedBy: updatedBy ?? null,
    })
  }
}

/**
 * 批量 upsert 设置项
 */
export async function upsertSystemSettings(
  items: ReadonlyArray<{
    category: SystemSettingCategory
    key: string
    value: string
    valueType: SystemSettingValueType
  }>,
  updatedBy?: string
): Promise<void> {
  for (const item of items) {
    await upsertSystemSetting({ ...item, updatedBy })
  }
}
