import { Request, Response } from 'express';
import { TenantKind } from '@prisma/client';
import { tenantKindOf } from './requireFeature';

/**
 * No role in an Enterprise tenant sees money (owner's rule, 6 Nov 2026): the
 * company pays salaries and deducts the room amount itself.
 *
 * These fields travel on shared routes (rooms, students, properties, mess
 * settings), so rather than trust every route to remember, the one place that
 * knows the tenant strips them from whatever comes in and goes out. Fields keep
 * their place and type, so a client's parser is unaffected. Other tenant kinds
 * pass straight through.
 */
const ZEROED = [
  'depositPaid',
  'depositRefunded',
  'depositHeld',
  'duesBalance',
  'refundDue',
  'messMonthlyFee',
  'messDailyRate',
  'lateFeeAmount',
  'gstRate',
  'gstThreshold',
  'earlyCheckInCharge',
  'lateCheckOutCharge',
  'ratePerNight',
  'totalSpend',
  'avgUnitCost',
  'stockValue',
];
const NULLED = [
  'monthlyRent',
  'nightlyRent',
  'rentDueDay',
  'depositAmount',
  'depositPaidAt',
  'depositMethod',
  'depositReference',
  'depositRefundedAt',
  'depositNote',
  'lateFeeCap',
  'refundAmount',
  'refundMethod',
  'refundReference',
  'monthlySalary',
  'salaryDay',
  'cost',
  'costExpenseId',
  'currentFee',
];
const SWITCHED_OFF = ['onlineCollectionEnabled', 'virtualAccountsEnabled'];

const OUTGOING = new Map<string, unknown>([
  ...ZEROED.map((k) => [k, 0] as const),
  ...NULLED.map((k) => [k, null] as const),
  ...SWITCHED_OFF.map((k) => [k, false] as const),
]);

function isPlainObject(value: unknown): value is Record<string, unknown> {
  if (value === null || typeof value !== 'object') return false;
  const proto = Object.getPrototypeOf(value);
  return proto === Object.prototype || proto === null;
}

/** A copy with money fields blanked. Dates and other class instances pass through. */
export function withoutMoney(value: unknown): unknown {
  if (Array.isArray(value)) return value.map(withoutMoney);
  if (!isPlainObject(value)) return value;
  return Object.fromEntries(
    Object.entries(value).map(([k, v]) => {
      // A null stays null: a field that was never set is not turned into a zero.
      if (OUTGOING.has(k)) return [k, v === null || v === undefined ? v : OUTGOING.get(k)];
      return [k, withoutMoney(v)];
    }),
  );
}

/** A copy with money fields removed, so a save ignores them as it does any unknown field. */
export function moneyDropped(value: unknown): unknown {
  if (Array.isArray(value)) return value.map(moneyDropped);
  if (!isPlainObject(value)) return value;
  return Object.fromEntries(
    Object.entries(value)
      .filter(([k]) => !OUTGOING.has(k))
      .map(([k, v]) => [k, moneyDropped(v)]),
  );
}

/** Called once the request's user is known. Does nothing unless the tenant is Enterprise. */
export async function keepMoneyOutOfEnterprise(req: Request, res: Response): Promise<void> {
  const tenantId = req.user?.tenantId;
  if (!tenantId || (await tenantKindOf(tenantId)) !== TenantKind.ENTERPRISE) return;
  // Some routers authenticate twice (a router-wide guard and a route's own).
  if (res.locals.moneyKeptOut) return;
  res.locals.moneyKeptOut = true;
  req.body = moneyDropped(req.body);
  const json = res.json.bind(res);
  res.json = (body: unknown) => json(withoutMoney(body));
}
