import "server-only";

import type { Setting } from "@prisma/client";
import { getActiveAccountProfile } from "@/lib/account-context";
import { getSessionUser } from "@/lib/auth/session";
import { prisma } from "@/lib/db";

export class SettingsError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "SettingsError";
  }
}

export async function getOrCreateSettingsForUser(userId: string): Promise<Setting> {
  const existing = await prisma.setting.findUnique({ where: { userId } });
  if (existing) return existing;

  return prisma.setting.create({
    data: { userId },
  });
}

/** 依目前 HTTP session 或 worker 暫存帳號的擁有者取得設定。 */
export async function getOrCreateSettings(): Promise<Setting> {
  const user = await getSessionUser();
  if (user) return getOrCreateSettingsForUser(user.id);

  const account = await getActiveAccountProfile();
  if (account?.userId) return getOrCreateSettingsForUser(account.userId);

  throw new SettingsError("無法取得使用者設定，請先登入");
}

/** 清除無主的舊版全域設定（一次性維護用）。 */
export async function purgeOrphanSettings() {
  await prisma.setting.deleteMany({ where: { userId: null } });
}