import { prisma } from "@/lib/db";

export type SkinName = "v1" | "v2";

export const SKINS: ReadonlyArray<{
  value: SkinName;
  label: string;
  tagline: string;
  description: string;
}> = [
  {
    value: "v1",
    label: "Finzone V1 — Premium Editorial",
    tagline: "Cream serif · drop-cap · long-form reading",
    description:
      "Phong cách báo in cao cấp: nền kem ấm, serif Fraunces / Newsreader, drop-cap đầu bài, viền mềm 4px. Tối ưu cho phân tích chuyên sâu và bài dài.",
  },
  {
    value: "v2",
    label: "Finzone V2 — Trader Terminal",
    tagline: "Mono uppercase · sharp edges · cyan accent",
    description:
      "Phong cách terminal trading: nền slate/navy, sans 700 + mono, viền 0px sắc cạnh, accent cyan/teal. Tối ưu cho tin nhanh, dữ liệu, bảng giá.",
  },
] as const;

export const DEFAULT_SKIN: SkinName = "v1";
const SETTING_KEY = "theme.active_skin";

export function isValidSkin(v: unknown): v is SkinName {
  return v === "v1" || v === "v2";
}

/** Read active skin from Setting table. Falls back to DEFAULT_SKIN if missing/invalid/DB-down. */
export async function loadActiveSkin(): Promise<SkinName> {
  try {
    const row = await prisma.setting.findUnique({
      where: { key: SETTING_KEY },
      select: { value: true },
    });
    const v = row?.value?.trim();
    return isValidSkin(v) ? v : DEFAULT_SKIN;
  } catch {
    return DEFAULT_SKIN;
  }
}

/** Upsert (creates the row on first save). Returns the value that was persisted. */
export async function saveActiveSkin(skin: SkinName, updatedBy: string): Promise<SkinName> {
  await prisma.setting.upsert({
    where: { key: SETTING_KEY },
    create: {
      key: SETTING_KEY,
      value: skin,
      category: "theme",
      isSecret: false,
      updatedBy,
    },
    update: { value: skin, updatedBy },
  });
  return skin;
}

export const ACTIVE_SKIN_KEY = SETTING_KEY;
