import { Role } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';

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

const SINGLETON_ID = 'singleton';

/** Read the settings row, creating it with defaults on first access. */
export function getCrmSettings() {
  return prismaUnscoped.crmSettings.upsert({
    where: { id: SINGLETON_ID },
    update: {},
    create: { id: SINGLETON_ID },
  });
}

export type CrmSettings = Awaited<ReturnType<typeof getCrmSettings>>;

export function updateCrmSettings(input: {
  emailsEnabled?: boolean;
  copySuperAdmin?: boolean;
  copyEmail?: string;
  contactSources?: string[];
  teamFollowUps?: boolean;
  aiEnabled?: boolean;
  aiFeatures?: string[];
  aiMonthlyBudgetUsd?: number;
  leadOwnerId?: string | null;
  leadOwnerOnLeave?: boolean;
  workDays?: number[];
  workStart?: string;
  workEnd?: string;
  responseMinutes?: number;
  demoDailyCap?: number;
  demoMinutes?: number;
  demoNoticeMinutes?: number;
  demoDaysAhead?: number;
  autoFirstMessage?: boolean;
  waAutoReply?: boolean;
  requireNextStep?: boolean;
  trialNudges?: boolean;
  hotBeds?: number;
}) {
  return prismaUnscoped.crmSettings.upsert({
    where: { id: SINGLETON_ID },
    update: input,
    create: { id: SINGLETON_ID, ...input },
  });
}

/** The super admin account whose email a blank copy address falls back to. */
export async function defaultCopyEmail(): Promise<string> {
  const admin = await prismaUnscoped.user.findFirst({
    where: { role: Role.SUPER_ADMIN, deactivatedAt: null },
    orderBy: { createdAt: 'asc' },
    select: { email: true },
  });
  return admin?.email ?? '';
}

/**
 * Where the super admin's copy of a CRM notification goes, or null when no
 * copy should be sent: notifications or copies are switched off, there is no
 * address, or the copy would land in an inbox that already gets the email —
 * the person who did the thing, or one of its recipients.
 *
 * Never used for account emails that carry a secret (invite and password
 * links, sign-in codes): those go to their owner only.
 */
export async function superAdminCopyAddress(opts: { actorEmail?: string | null; recipients?: string[] } = {}): Promise<string | null> {
  const s = await getCrmSettings();
  if (!s.emailsEnabled || !s.copySuperAdmin) return null;
  const address = (s.copyEmail.trim() || (await defaultCopyEmail())).toLowerCase();
  if (!address) return null;
  if (opts.actorEmail && opts.actorEmail.toLowerCase() === address) return null;
  if (opts.recipients?.some((r) => r.toLowerCase() === address)) return null;
  return address;
}
