import type { GlAccountType } from '@prisma/client';
import { TRPCError } from '@trpc/server';

/*
 * The shapes of the codes the office keys into its ERP (Multiable) when it
 * imports from Excel. They are the ERP's codes, not ours, so a malformed one is
 * refused here rather than discovered at import:
 *
 *   landlord code   2 letters                                   WF
 *   tenant code     landlord code + 4 letters/digits + 2 digits  WFCHAN01
 *   account code    4-2-4 digits                                1234-56-7890
 *
 * Every router that writes one goes through these, so the rule is stated once.
 * Messages are catalogued in apps/admin/src/i18n/locales/{en,zh-HK}/errors.json.
 */

const LANDLORD_CODE = /^[A-Z]{2}$/;
const TENANT_CODE = /^[A-Z]{2}[A-Z0-9]{4}[0-9]{2}$/;
const ACCOUNT_CODE = /^[0-9]{4}-[0-9]{2}-[0-9]{4}$/;

/** Upper-cased and checked; throws if it is not two letters. */
export function landlordCode(raw: string): string {
  const code = raw.trim().toUpperCase();
  if (!LANDLORD_CODE.test(code)) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Landlord code must be 2 letters, e.g. WF' });
  return code;
}

/** Null when blank; otherwise checked. Undefined passes through untouched, so a
 *  partial update that does not mention it leaves it alone. */
export function accountCode(raw: string | null | undefined): string | null | undefined {
  if (raw === undefined) return undefined;
  const code = raw?.trim() ?? '';
  if (code === '') return null;
  if (!ACCOUNT_CODE.test(code)) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Account code must look like 1234-56-7890' });
  return code;
}

/** True when it has the ERP's account-code shape — for an import, which reports
 *  a bad row and carries on rather than stopping at it. */
export function isAccountCode(code: string): boolean {
  return ACCOUNT_CODE.test(code);
}

/** The type the ERP's numbering gives an account: 1-3 assets, 4-5 liabilities,
 *  7 income, 8 expenses, the rest (6 capital and reserves, 9999 suspense)
 *  equity. The office's chart, not a rule of accounting: an account's type can
 *  be changed on the chart-of-accounts page. The chart-of-accounts migration
 *  typed the codes it carried over the same way. */
export function accountTypeFor(code: string): GlAccountType {
  switch (code[0]) {
    case '1':
    case '2':
    case '3':
      return 'ASSET';
    case '4':
    case '5':
      return 'LIABILITY';
    case '7':
      return 'INCOME';
    case '8':
      return 'EXPENSE';
    default:
      return 'EQUITY';
  }
}

/** Upper-cased and checked against its landlord's code. */
export function tenantCode(raw: string, ofLandlord: string): string {
  const code = raw.trim().toUpperCase();
  if (!TENANT_CODE.test(code)) {
    throw new TRPCError({
      code: 'BAD_REQUEST',
      message: 'Tenant code must be 8 characters: the landlord code, 4 letters or digits, then 2 digits — e.g. WFCHAN01',
    });
  }
  if (!code.startsWith(ofLandlord)) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: `Tenant code ${code} must start with its landlord's code ${ofLandlord}` });
  }
  return code;
}

/** What a new tenant code for this landlord and name should start with: the
 *  landlord's code and the first four letters or digits of the name. Shorter
 *  when the name has fewer — a Chinese-only name gives none — and then it is
 *  left for whoever is typing to finish. */
export function tenantCodeStem(ofLandlord: string, name: string): string {
  return ofLandlord + name.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 4);
}
