import { prismaUnscoped } from '../../lib/prisma';

/**
 * Platform-wide settings — one row, owned by the SUPER_ADMIN.
 *
 * Platform-level like Plan and the subscription ledger: deliberately absent
 * from TENANT_SCOPED_MODELS and only ever reached through the unscoped client.
 */

const SINGLETON_ID = 'singleton';

export type PlatformSettings = Awaited<ReturnType<typeof getSettings>>;

/**
 * Read the settings row, creating it with defaults on first access so a fresh
 * install never has to be seeded separately.
 */
export async function getSettings() {
  return prismaUnscoped.platformSettings.upsert({
    where: { id: SINGLETON_ID },
    update: {},
    create: { id: SINGLETON_ID },
  });
}

export type BillingProfileField =
  | 'billingCompanyName'
  | 'billingEmail'
  | 'billingPhone'
  | 'billingWebsite'
  | 'billingGstin'
  | 'billingPan'
  | 'billingAddress'
  | 'billingCity'
  | 'billingState'
  | 'billingCountry'
  | 'billingZip';

export async function updateSettings(
  input: {
    platformName?: string;
    supportEmail?: string;
    supportPhone?: string;
    websiteUrl?: string;
    invoiceDueDay?: number;
    planRemindersEnabled?: boolean;
    planReminderDays?: number[];
    planWeeklySummary?: boolean;
  } & Partial<Record<BillingProfileField, string>>,
) {
  return prismaUnscoped.platformSettings.upsert({
    where: { id: SINGLETON_ID },
    update: input,
    create: { id: SINGLETON_ID, ...input },
  });
}

/**
 * How the platform introduces itself to tenants — used in the message a
 * suspended hostel sees at sign-in. Falls back to sane defaults so this never
 * blocks auth if the row is somehow missing.
 */
export async function getSupportIdentity(): Promise<{ platformName: string; supportEmail: string }> {
  try {
    const s = await prismaUnscoped.platformSettings.findUnique({ where: { id: SINGLETON_ID } });
    return {
      platformName: s?.platformName || 'HostelCare',
      supportEmail: s?.supportEmail || '',
    };
  } catch {
    return { platformName: 'HostelCare', supportEmail: '' };
  }
}
