import { prisma } from './prisma';

export type SiteSettings = {
  requireLoginForContactDetails: boolean;
};

const SETTINGS_ID = 'default';

const DEFAULT_SETTINGS: SiteSettings = {
  requireLoginForContactDetails: true,
};

function mergeSettings(input: Partial<SiteSettings> | null | undefined): SiteSettings {
  return {
    requireLoginForContactDetails:
      input?.requireLoginForContactDetails ?? DEFAULT_SETTINGS.requireLoginForContactDetails,
  };
}

export async function getSiteSettings(): Promise<SiteSettings> {
  try {
    const existing = await prisma.siteSettings.findUnique({ where: { id: SETTINGS_ID } });
    if (!existing) {
      return DEFAULT_SETTINGS;
    }
    return mergeSettings(existing);
  } catch (error) {
    console.error('Failed to load site settings, falling back to defaults', error);
    return DEFAULT_SETTINGS;
  }
}

export async function updateSiteSettings(input: Partial<SiteSettings>): Promise<SiteSettings> {
  const current = await getSiteSettings();
  const data = mergeSettings({ ...current, ...input });
  const saved = await prisma.siteSettings.upsert({
    where: { id: SETTINGS_ID },
    update: data,
    create: { id: SETTINGS_ID, ...data },
  });
  return mergeSettings(saved);
}
