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

/** Referral program: every subscriber holds a personal referral code. The
 *  two sides of every referral:
 *   • the NEW institution registering with the code gets the platform's
 *     referral discount (referralDiscountPct, default 10%) once — on the
 *     first subscription approved after registering;
 *   • the OWNER of the used code earns a commission (referralCommissionPct,
 *     default 10%) of the total YEARLY amount each time a referred
 *     institution takes a yearly subscription (referral_commissions ledger;
 *     payouts handled out-of-band by the central team). */

export const REFERRAL_DISCOUNT_KEY = "referralDiscountPct";
export const DEFAULT_REFERRAL_DISCOUNT_PCT = 10;

export const REFERRAL_COMMISSION_KEY = "referralCommissionPct";
export const DEFAULT_REFERRAL_COMMISSION_PCT = 10;

/** unambiguous alphabet — no 0/O/1/I */
const CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";

export function clampReferralPct(v: unknown, fallback: number): number {
  const n = Number(v);
  if (!Number.isFinite(n)) return fallback;
  return Math.min(90, Math.max(0, Math.round(n)));
}

/** Platform-wide referral discount percentage the central admin configured. */
export async function getReferralDiscountPct(): Promise<number> {
  const row = await prisma.platformSetting.findUnique({
    where: { key: REFERRAL_DISCOUNT_KEY },
    select: { value: true },
  });
  return clampReferralPct(row?.value, DEFAULT_REFERRAL_DISCOUNT_PCT);
}

/** Platform-wide referral commission percentage the code OWNER earns of a
 *  referred institution's total yearly amount (each yearly subscription). */
export async function getReferralCommissionPct(): Promise<number> {
  const row = await prisma.platformSetting.findUnique({
    where: { key: REFERRAL_COMMISSION_KEY },
    select: { value: true },
  });
  return clampReferralPct(row?.value, DEFAULT_REFERRAL_COMMISSION_PCT);
}

export async function setReferralCommissionPct(pct: number): Promise<number> {
  const value = String(clampReferralPct(pct, DEFAULT_REFERRAL_COMMISSION_PCT));
  await prisma.platformSetting.upsert({
    where: { key: REFERRAL_COMMISSION_KEY },
    update: { value },
    create: { key: REFERRAL_COMMISSION_KEY, value },
  });
  return Number(value);
}

export async function setReferralDiscountPct(pct: number): Promise<number> {
  const value = String(clampReferralPct(pct, DEFAULT_REFERRAL_DISCOUNT_PCT));
  await prisma.platformSetting.upsert({
    where: { key: REFERRAL_DISCOUNT_KEY },
    update: { value },
    create: { key: REFERRAL_DISCOUNT_KEY, value },
  });
  return Number(value);
}

/** Lazily issue a unique referral code (REF-XXXXXXXX) for an institution. */
export async function ensureReferralCode(institutionId: number): Promise<string> {
  const inst = await prisma.institution.findUnique({
    where: { id: institutionId },
    select: { referralCode: true },
  });
  if (inst?.referralCode) return inst.referralCode;
  return resetReferralCode(institutionId);
}

/** Force a freshly generated code (central-admin reset). */
export async function resetReferralCode(institutionId: number): Promise<string> {
  for (let attempt = 0; attempt < 5; attempt++) {
    let suffix = "";
    for (let i = 0; i < 8; i++) {
      suffix += CODE_ALPHABET[Math.floor(Math.random() * CODE_ALPHABET.length)];
    }
    const code = `REF-${suffix}`;
    try {
      const updated = await prisma.institution.update({
        where: { id: institutionId },
        data: { referralCode: code },
        select: { referralCode: true },
      });
      return updated.referralCode!;
    } catch {
      /* unique collision — retry with a fresh suffix */
    }
  }
  throw new Error("Could not generate a referral code");
}
