/**
 * Functional smoke: a charge that follows the property's standard charge.
 *
 * Every building changes its management fee from time to time, by a notice from
 * its management company giving the date it takes effect. A lease's management
 * fee used to be a fixed amount of its own, changed only when somebody stepped
 * it from the property's rate review; the owner wants the debit note to follow
 * the notice by itself, and the notice to appear on the note when the fee
 * changes. A charge rule now follows the standard (ChargeRule.followsStandard):
 * billed at the property's figure for its units as in force on each day.
 *
 * What has to hold, and is asserted: a following rule bills the figure in force
 * for each period; a mid-month change splits a daily-prorated month by days and
 * reaches a whole-month rule from its next period; a whole-lease rule bills its
 * units' figures added up, each unit its own on a split note; a rule with no
 * figure yet bills its own amount; correcting a figure reaches a rebuilt draft;
 * the rate review leaves following rules alone; the note that first bills a new
 * figure carries its notice — a photo on a page, a PDF's pages after the note's
 * — and the next note does not; a one-off charge cannot follow; a price kept
 * apart is listed and can be made to follow; the rent roll reads today's figure.
 *
 * Runs in its own organisation. Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/standard-follow-smoke.ts
 */
import 'reflect-metadata';
import { ConfigService } from '@nestjs/config';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { PDFDocument } from 'pdf-lib';
import { ApprovalService } from '../src/approvals/approval.service';
import { StorageService } from '../src/attachments/storage.service';
import { BillingService } from '../src/billing/billing.service';
import { NumberService } from '../src/common/number.service';
import { DocumentService } from '../src/documents/document.service';
import { PdfService } from '../src/documents/pdf.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { ReportsService } from '../src/reports/reports.service';
import { correctStandardCharge, reviewStandardCharge } from '../src/standard-charges/standard-charge.service';
import { leasesRouter } from '../src/trpc/routers/leases.router';
import { standardChargesRouter } from '../src/trpc/routers/standard-charges.router';
import type { AuthUser } from '../src/trpc/auth-user';
import type { Context } from '../src/trpc/trpc';

const prisma = new PrismaService();
const config = new ConfigService();
const storage = new StorageService(config);
const pdf = new PdfService(config);
const documents = new DocumentService(prisma, storage, pdf);
const billing = new BillingService(prisma, new LedgerService(), new NumberService(), new EventEmitter2(), new ApprovalService(prisma));
const reports = new ReportsService(prisma);

let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };
async function refused(fn: () => Promise<unknown>): Promise<string> {
  try { await fn(); return ''; } catch (e) { return e instanceof Error ? e.message : String(e); }
}

const ORG_CODE = 'ZZ-FLW-ORG';
const D = (iso: string) => new Date(`${iso}T00:00:00.000Z`);
/** A 1×1 PNG, the smallest photo of a notice. */
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==', 'base64');

function staffCtx(orgId: string): Context {
  const user: AuthUser = {
    id: 'zz-flw-staff', email: 'zz-flw@rms.local', name: 'ZZ FLW', tenantId: null, mustChangePassword: false, roles: ['ADMIN'],
    permissions: ['lease.read', 'lease.create', 'lease.update', 'property.read', 'property.update'],
  };
  return { prisma, user, organizationId: orgId } as unknown as Context;
}

async function main() {
  await purge();
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'ZZ Follow standard org' } })).id;
  await prisma.numberSequence.create({ data: { organizationId: orgId, docType: 'INVOICE', prefix: 'ZFN-', padding: 6 } });
  const mgmt = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'MGMT_FEE', nameEn: 'Management Fee', category: 'RECURRING' } });
  const noticeType = await prisma.referenceValue.create({ data: { organizationId: orgId, domain: 'NOTICE_TYPE', code: 'MGMT_FEE_ADJUSTMENT', nameEn: 'Management Fee Adjustment' } });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Follow Tenant' } });
  const P = await prisma.property.create({ data: { organizationId: orgId, name: 'ZZ Follow Tower', units: { create: [{ name: 'A' }, { name: 'B' }, { name: 'C' }] } }, include: { units: true } });
  const Q = await prisma.property.create({ data: { organizationId: orgId, name: 'ZZ Follow Plaza', units: { create: [{ name: 'Q1' }] } }, include: { units: true } });
  const u = Object.fromEntries([...P.units, ...Q.units].map((x) => [x.name, x.id]));
  const std = (propertyId: string, unitId: string | null, amount: string, from: string) =>
    prisma.standardCharge.create({ data: { organizationId: orgId, propertyId, unitId, chargeTypeId: mgmt.id, amount, effectiveFrom: D(from) } });
  await std(P.id, null, '1000', '2026-01-01');
  await std(P.id, u.B, '1500', '2026-01-01');
  const march = await std(P.id, null, '1200', '2026-03-01');
  await std(Q.id, null, '800', '2026-01-01');
  await std(Q.id, null, '900', '2026-02-15');

  // The notice of the March change: a photo and a PDF of the letter.
  const notice = await prisma.propertyNotice.create({ data: { organizationId: orgId, propertyId: P.id, date: D('2026-02-10'), typeId: noticeType.id, remark: 'ZZ new fee from March', standardChargeId: march.id } });
  const letter = await PDFDocument.create();
  letter.addPage();
  letter.addPage();
  const file = async (filename: string, mimeType: string, bytes: Buffer) =>
    prisma.attachment.create({
      data: { organizationId: orgId, ownerType: 'PROPERTY_NOTICE', ownerId: notice.id, filename, mimeType, sizeBytes: bytes.length, storageKey: await storage.save(bytes, mimeType === 'application/pdf' ? 'pdf' : 'png') },
    });
  await file('zz-notice.png', 'image/png', PNG);
  await file('zz-notice.pdf', 'application/pdf', Buffer.from(await letter.save()));

  const lease = (ref: string, propertyId: string, units: string[], rules: { unitId?: string; amount: string; proration?: 'DAILY' | 'FULL_MONTH'; followsStandard?: boolean; firstInvoiceOnly?: boolean; frequencyMonths?: number }[]) =>
    prisma.lease.create({
      data: {
        organizationId: orgId, reference: `ZZ-FLW-${ref}`, tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
        startDate: D('2026-01-01'), endDate: D('2030-12-31'), depositMonths: 0,
        units: { create: units.map((n) => ({ unitId: u[n] })) },
        chargeRules: {
          create: rules.map((r, i) => ({
            chargeTypeId: mgmt.id, unitId: r.unitId ?? null, amount: r.amount, frequencyMonths: r.frequencyMonths ?? 1, timing: 'ADVANCE',
            proration: r.proration ?? 'DAILY', firstInvoiceOnly: r.firstInvoiceOnly ?? false, followsStandard: r.followsStandard ?? true, sortOrder: i,
          })),
        },
      },
    });
  const lines = async (leaseId: string, period: string, unitIds?: string[]) => {
    const note = await billing.generateDraft({ organizationId: orgId, leaseId, period, ...(unitIds ? { unitIds } : {}) });
    return { note, lines: note.lines.filter((l) => l.chargeTypeId === mgmt.id) };
  };
  const amounts = (ls: { amount: { toFixed(n: number): string } }[]) => ls.map((l) => l.amount.toFixed(2)).join(' ');

  console.log('A. A following rule bills the standard figure of each period');
  const L1 = await lease('L1', P.id, ['A'], [{ unitId: u.A, amount: '999' }]);
  const jan = await lines(L1.id, '2026-01');
  ck('A1 January at the property’s 1000, not the rule’s own 999', amounts(jan.lines) === '1000.00', amounts(jan.lines));
  const mar = await lines(L1.id, '2026-03');
  ck('A2 March at the new 1200 from its effective date', amounts(mar.lines) === '1200.00', amounts(mar.lines));
  const marMeta = mar.lines[0]?.meta as { standardChanged?: string[] } | null;
  ck('A3 the March line names the change it is the first to bill', marMeta?.standardChanged?.join() === march.id, JSON.stringify(marMeta));
  const apr = await lines(L1.id, '2026-04');
  ck('A4 April at 1200 too, and names no change', amounts(apr.lines) === '1200.00' && !(apr.lines[0]?.meta as { standardChanged?: string[] } | null)?.standardChanged, JSON.stringify(apr.lines[0]?.meta));
  await std(P.id, null, '1300', '2026-05-16');
  const may = await lines(L1.id, '2026-05');
  // 1200 × 15/31 = 580.65; 1300 × 16/31 = 670.97.
  ck('A5 a mid-month change splits a month prorated by day', amounts(may.lines) === '580.65 670.97', amounts(may.lines));

  console.log('\nB. A whole-month rule takes a mid-month change from its next period');
  const L2 = await lease('L2', Q.id, ['Q1'], [{ unitId: u.Q1, amount: '800', proration: 'FULL_MONTH' }]);
  const qFeb = await lines(L2.id, '2026-02');
  const qMar = await lines(L2.id, '2026-03');
  ck('B1 February, changed on the 15th, is billed whole at the old 800 — once', amounts(qFeb.lines) === '800.00', amounts(qFeb.lines));
  ck('B2 March at the new 900, naming the change', amounts(qMar.lines) === '900.00' && Boolean((qMar.lines[0]?.meta as { standardChanged?: string[] } | null)?.standardChanged?.length), amounts(qMar.lines));

  console.log('\nC. A whole-lease rule bills its units’ figures, each unit its own on a split note');
  const L3 = await lease('L3', P.id, ['A', 'B'], [{ amount: '2500' }]);
  ck('C1 January: A at the property’s 1000 and B at its own 1500, 2500', amounts((await lines(L3.id, '2026-01')).lines) === '2500.00');
  ck('C2 a note for B alone bills B’s own 1500, not half', amounts((await lines(L3.id, '2026-02', [u.B])).lines) === '1500.00');

  console.log('\nD. Without a figure, the rule’s own amount');
  const elsewhere = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'AIRCON', nameEn: 'Aircon', category: 'RECURRING' } });
  const L4 = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: 'ZZ-FLW-L4', tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD',
      startDate: D('2026-01-01'), endDate: D('2030-12-31'), depositMonths: 0, units: { create: [{ unitId: u.C }] },
      chargeRules: { create: [{ chargeTypeId: elsewhere.id, unitId: u.C, amount: '450', frequencyMonths: 1, timing: 'ADVANCE', proration: 'DAILY', firstInvoiceOnly: false, followsStandard: true, sortOrder: 0 }] },
    },
  });
  const air = await billing.generateDraft({ organizationId: orgId, leaseId: L4.id, period: '2026-01' });
  ck('D1 a charge with no standard figure bills the rule’s own 450', air.lines.map((l) => l.amount.toFixed(2)).join() === '450.00');

  console.log('\nE. A correction reaches a rebuilt draft; the review leaves following rules alone');
  await correctStandardCharge(prisma, orgId, march.id, { amount: '1250', effectiveFrom: D('2026-03-01'), note: null });
  await billing.regenerateDraft({ organizationId: orgId, invoiceId: mar.note.id });
  const rebuilt = await prisma.invoiceLine.findMany({ where: { invoiceId: mar.note.id, chargeTypeId: mgmt.id } });
  ck('E1 March’s draft, rebuilt, bills the corrected 1250', amounts(rebuilt) === '1250.00', amounts(rebuilt));
  const fixedLease = await lease('L5', P.id, ['A'], [{ unitId: u.A, amount: '1000', followsStandard: false }]);
  const raise = await std(P.id, null, '1400', '2026-09-01');
  const review = await reviewStandardCharge(prisma, orgId, raise.id);
  ck('E2 the review offers the fixed price, not the following one', review.affected.some((a) => a.leaseId === fixedLease.id) && !review.affected.some((a) => a.leaseId === L1.id));
  ck('E3 and says why the following one is left out', review.skipped.some((s) => s.leaseId === L1.id && s.reason === 'FOLLOWS_STANDARD'));

  console.log('\nF. The notice goes on the note that first bills the new figure');
  const marHtml = (await documents.invoiceHtml(orgId, mar.note.id)).html;
  const aprHtml = (await documents.invoiceHtml(orgId, apr.note.id)).html;
  ck('F1 March’s note names the charge, shows the photo, and keeps the file name off the page',
    marHtml.includes('Notice of change') && marHtml.includes('Management Fee') && marHtml.includes('data:image/png;base64,') && !marHtml.includes('zz-notice.pdf') && !marHtml.includes('notice of'));
  ck('F2 April’s note has none', !aprHtml.includes('Notice of change'));
  const renderer = pdf.rendererStatus();
  if (!renderer.ok) {
    console.log(`  — F3 skipped: no PDF renderer here (${renderer.source}: ${renderer.detail ?? ''})`);
  } else {
    const withNotice = await PDFDocument.load(await documents.invoicePdf(orgId, mar.note.id));
    const without = await PDFDocument.load(await documents.invoicePdf(orgId, apr.note.id));
    // March: the note, one page naming the photo and the PDF, then the letter's two pages.
    ck('F3 the letter’s pages follow March’s note', withNotice.getPageCount() === without.getPageCount() + 3, `${withNotice.getPageCount()} vs ${without.getPageCount()}`);
  }

  console.log('\nG. Following is for recurring charges; a price apart is listed and can follow');
  const leases = leasesRouter.createCaller(staffCtx(orgId));
  const oneOff = await refused(() =>
    leases.create({
      reference: 'ZZ-FLW-L9', tenantId: tenant.id, status: 'ACTIVE', currency: 'HKD', startDate: '2026-01-01', endDate: '2026-12-31',
      unitIds: [u.A], billingGroups: {}, labels: [],
      chargeRules: [{ chargeTypeId: mgmt.id, amount: '500', frequencyMonths: 0, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: true, unitId: u.A, followsStandard: true }],
    }),
  );
  ck('G1 a one-off charge cannot follow', oneOff.includes('cannot follow the standard charge'), oneOff);
  const page = await standardChargesRouter.createCaller(staffCtx(orgId)).all();
  ck('G2 the records page lists every building’s figures for the management fee', page.chargeTypeId === mgmt.id && page.rows.length === 7 && page.rows.some((r) => r.propertyName === 'ZZ Follow Plaza'), `${page.rows.length}`);
  const marchRow = page.rows.find((r) => r.id === march.id);
  ck('G3 with the notice and its files beside the figure', marchRow?.notices[0]?.files.length === 2 && marchRow.status === 'SUPERSEDED', JSON.stringify(marchRow?.notices));
  const apart = page.notFollowing.find((r) => r.leaseId === fixedLease.id);
  ck('G4 the price kept apart is listed, beside today’s standard', apart?.amount === '1000.00' && apart.standardNow !== null, JSON.stringify(apart));
  await leases.followStandard({ ruleId: apart!.ruleId });
  const after = await standardChargesRouter.createCaller(staffCtx(orgId)).all();
  ck('G5 made to follow, it leaves the list', !after.notFollowing.some((r) => r.leaseId === fixedLease.id));
  const roll = await reports.rentRoll(orgId);
  const l1Roll = roll.groups[0]?.rows.find((r) => r.reference === 'ZZ-FLW-L1');
  // In force today: the property's 1400 from September.
  ck('G6 the rent roll reads today’s standard figure for a following rule', l1Roll?.monthlyCharge === '1400.00', JSON.stringify(l1Roll));
}

async function purge() {
  const org = await prisma.organization.findUnique({ where: { code: ORG_CODE }, select: { id: true } });
  if (!org) return;
  const where = { organizationId: org.id };
  const files = await prisma.attachment.findMany({ where, select: { id: true, storageKey: true } });
  for (const f of files) await storage.remove(f.storageKey).catch(() => undefined);
  await prisma.attachment.deleteMany({ where });
  const invIds = (await prisma.invoice.findMany({ where, select: { id: true } })).map((i) => i.id);
  await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invIds } } });
  await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });
  await prisma.propertyNotice.deleteMany({ where });
  await prisma.standardCharge.deleteMany({ where });
  const leaseIds = (await prisma.lease.findMany({ where, select: { id: true } })).map((l) => l.id);
  await prisma.chargeRule.deleteMany({ where: { leaseId: { in: leaseIds } } });
  await prisma.leaseUnit.deleteMany({ where: { leaseId: { in: leaseIds } } });
  await prisma.lease.deleteMany({ where: { id: { in: leaseIds } } });
  const props = (await prisma.property.findMany({ where, select: { id: true } })).map((p) => p.id);
  await prisma.unit.deleteMany({ where: { propertyId: { in: props } } });
  await prisma.property.deleteMany({ where: { id: { in: props } } });
  await prisma.tenant.deleteMany({ where });
  await prisma.chargeType.deleteMany({ where });
  await prisma.referenceValue.deleteMany({ where });
  await prisma.numberSequence.deleteMany({ where });
  await prisma.organization.delete({ where: { id: org.id } });
}

async function cleanup() {
  try { await purge(); console.log('\nCleanup: OK'); }
  catch (e) { console.log(`\nCleanup WARNING: ${e instanceof Error ? e.message : e}`); }
}

main()
  .catch((e) => { fail++; console.log(`\nFATAL: ${e instanceof Error ? e.stack : e}`); })
  .finally(async () => {
    await cleanup();
    await pdf.onModuleDestroy().catch(() => undefined);
    await prisma.$disconnect();
    console.log(`\n==== ${pass} passed, ${fail} failed ====`);
    process.exit(fail > 0 ? 1 : 0);
  });
