// Financial report shapes — Nest-free so the router + client can import them.
// Everything is grouped by currency: with no FX, HKD and SGD books are separate
// and must never be summed together.
import type { Currency, InvoiceStatus, LeaseStatus } from '@prisma/client';

export interface TrialBalanceRow {
  code: string;
  name: string;
  type: string;
  debit: string;
  credit: string;
}
export interface TrialBalanceGroup {
  currency: Currency;
  rows: TrialBalanceRow[];
  totalDebit: string;
  totalCredit: string;
  balanced: boolean;
}
export interface TrialBalance {
  asOf: string;
  groups: TrialBalanceGroup[];
}

export interface ArAgingBuckets {
  current: string;
  d1_30: string;
  d31_60: string;
  d61_90: string;
  d90plus: string;
  total: string;
}
/** One lease's receivable: its tenant, and its premises as the debit note
 *  prints them, on one line. */
export interface ArAgingRow extends ArAgingBuckets {
  tenantId: string;
  tenantName: string;
  leaseId: string;
  leaseReference: string;
  premises: string;
}
export interface ArAgingGroup {
  currency: Currency;
  rows: ArAgingRow[];
  totals: ArAgingBuckets;
}
export interface ArAging {
  asOf: string;
  /** Every tenant owing at the date, whichever were asked for — what to pick from. */
  tenants: { id: string; name: string }[];
  groups: ArAgingGroup[];
}

export interface IncomeStatementLine {
  code: string;
  name: string;
  amount: string;
}
export interface IncomeStatementGroup {
  currency: Currency;
  income: IncomeStatementLine[];
  expense: IncomeStatementLine[];
  totalIncome: string;
  totalExpense: string;
  net: string;
}
export interface IncomeStatement {
  from: string;
  to: string;
  groups: IncomeStatementGroup[];
}

export interface RentRollRow {
  reference: string;
  tenantName: string;
  propertyName: string;
  units: string;
  startDate: Date;
  endDate: Date;
  monthlyCharge: string;
}
export interface RentRollGroup {
  currency: Currency;
  rows: RentRollRow[];
  totalMonthly: string;
}
export interface RentRoll {
  groups: RentRollGroup[];
}

export interface CollectionsMethod {
  method: string;
  amount: string;
  count: number;
}
export interface CollectionsGroup {
  currency: Currency;
  methods: CollectionsMethod[];
  total: string;
  count: number;
}
export interface Collections {
  from: string;
  to: string;
  groups: CollectionsGroup[];
}

export interface DashboardMoney {
  currency: Currency;
  amount: string;
}
export interface DashboardRate {
  currency: Currency;
  rate: string; // percent, 1dp, e.g. "94.8"
}
export interface Dashboard {
  month: string; // "YYYY-MM" — the window invoicedThisMonth covers
  activeLeases: number; // a count, not money: not grouped by currency
  outstandingAr: DashboardMoney[];
  invoicedThisMonth: DashboardMoney[];
  /** No row for a currency with nothing charged — 0/0 is undefined, not 0%. */
  collectionRate: DashboardRate[];
}

/** A name the office keeps in both languages; the admin app shows the one it reads in. */
export interface Bilingual {
  en: string;
  zh: string | null;
}

/** Where a note stood as at the report's date: nothing of it paid, part, or all. */
export type Settlement = 'UNSETTLED' | 'PARTIAL' | 'SETTLED';

/** What the outstanding debit notes report is run for. The dates narrow which
 *  notes are read; everything else about what is shown is the layout's. */
export interface OutstandingInvoiceQuery {
  asOf: string;
  settlement: Settlement[];
  /** Notes not issued yet (draft, awaiting approval, approved), at their face value. */
  includeUnissued: boolean;
  issueFrom?: string;
  issueTo?: string;
  dueFrom?: string;
  dueTo?: string;
  periodFrom?: string;
  periodTo?: string;
}

/**
 * One debit note as at a date — what it charged and what became of it, read
 * from the ledger, beside everything about whom and what it billed. Every row
 * holds every field: which of them make up the report is the layout's choice.
 * Dates are Hong Kong calendar days, "YYYY-MM-DD"; money is a 2dp string.
 *
 * outstanding = invoiceAmount + broughtForward − received − depositApplied − carriedForward
 */
export interface OutstandingInvoiceRow {
  id: string;
  number: string | null;
  status: InvoiceStatus;
  settlement: Settlement;
  currency: Currency;
  billingPeriod: string;
  issueDate: string | null;
  dueDate: string;
  bankAccount: string | null;
  chargeTypes: Bilingual[];
  units: string;
  note: string | null;

  /** The note's own charges, net of any waiver or offset printed on it. */
  invoiceAmount: string;
  /** Balances carried onto this note from earlier ones. */
  broughtForward: string;
  /** Paid by receipts, a deposit receipt's credit included. */
  received: string;
  /** Paid out of a deposit held. */
  depositApplied: string;
  /** Moved on to a later note. */
  carriedForward: string;
  outstanding: string;

  tenantCode: string | null;
  tenantName: string;
  tenantNameZh: string | null;
  attention: string | null;
  phone: string | null;
  email: string | null;
  /** The tenant's receivable account in the company's ERP books. */
  arAccount: string | null;

  leaseReference: string;
  leaseStatus: LeaseStatus;
  leaseStart: string;
  leaseEnd: string;
  leaseType: Bilingual | null;
  leaseUsage: Bilingual | null;
  leaseLabels: string[];

  building: string;
  propertyCodes: string;
  address: string | null;
  region: Bilingual | null;
  category: Bilingual | null;

  landlordCode: string | null;
  landlordName: string | null;
  landlordNameZh: string | null;
}

export interface OutstandingInvoices {
  asOf: string;
  rows: OutstandingInvoiceRow[];
}

/**
 * How a tenant's monthly statement is drawn up — the options the ERP's own
 * statement printing offers, where they mean something here. Dates are Hong
 * Kong calendar days, "YYYY-MM-DD".
 */
export interface StatementQuery {
  from: string;
  to: string;
  /** Age what is owed at the end by due date, or by issue date. A note not
   *  due yet is "not yet due" either way. */
  agingBasis: 'due' | 'issue';
  /** List each note still owing at the start, rather than one balance b/f. */
  openingItems: boolean;
  /** One line per document — a payment of three notes is one line — or one
   *  per note it moved. */
  groupEntries: boolean;
  /** Only these leases; all of them otherwise. */
  leaseIds?: string[];
}

/** What a statement line is, for a template that words them its own way. */
export type StatementRowKind =
  | 'BALANCE_BF' // the opening balance, as one line
  | 'OPENING_ITEM' // a note still owing at the start
  | 'INVOICE' // a debit note issued
  | 'PAYMENT' // a receipt
  | 'CREDIT_APPLIED' // a deposit receipt's money drawn onto a note
  | 'DEPOSIT_APPLIED' // a security deposit used to pay, or that use undone
  | 'VOID' // a debit note voided
  | 'REVERSAL' // a payment bounced, or a drawing taken back
  | 'OTHER';

/** One line of a statement. Money is a 2dp string; a debit adds to what the
 *  tenant owes, a credit takes from it, and the balance runs down the page. */
export interface StatementRow {
  kind: StatementRowKind;
  date: string | null;
  number: string;
  description: string;
  /** The document's own amount — a note's charges, a payment's total — which
   *  can be more than it moved here: one payment can settle two leases. */
  amount: string | null;
  debit: string | null;
  credit: string | null;
  balance: string;
}

/** What is owed at the end, by age; the buckets add up to the closing balance. */
export interface StatementAging {
  notYetDue: string;
  d0_30: string;
  d31_60: string;
  d61_90: string;
  over90: string;
}

/** One lease's statement for the period. */
export interface Statement {
  leaseId: string;
  leaseReference: string;
  leaseStatus: LeaseStatus;
  currency: Currency;

  tenantId: string;
  tenantName: string;
  tenantNameZh: string | null;
  tenantCode: string | null;
  attention: string | null;
  phone: string | null;
  email: string | null;

  landlordCode: string | null;
  landlordName: string | null;
  building: string;
  units: string[];
  address: string | null;
  region: Bilingual | null;

  opening: string;
  debit: string;
  credit: string;
  closing: string;
  aging: StatementAging;
  /** Security deposits held for the lease at the end. */
  deposit: string;
  /** Deposit-receipt money the lease holds and no note has used yet. */
  unallocated: string;
  /** Anything to print: a balance at either end, a movement, a deposit or credit held. */
  active: boolean;
  rows: StatementRow[];
}

export interface Statements {
  from: string;
  to: string;
  statements: Statement[];
}
