/**
 * Functional smoke for tenant-declared meter readings. Standalone, self-cleaning.
 *
 * A meter inside a tenant's own flat can only be read by the tenant, so the
 * number arrives from the party being billed from it. The point of the whole
 * feature is therefore the gate: a declaration is priced and billable only once
 * someone has checked it against the dial photo. C is the assertion that matters.
 *
 * F–H hold the two ends of that gate shut from the office's side: a reading that
 * has already gone out on a note cannot be edited underneath it, and the figure
 * the staff form opens the NEXT reading from is a confirmed one — never a
 * declaration still waiting, or one already sent back.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/tenant-reading-smoke.ts
 */
import 'reflect-metadata';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { BillingService } from '../src/billing/billing.service';
import { ApprovalService } from '../src/approvals/approval.service';
import { NumberService } from '../src/common/number.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { MeteringService } from '../src/metering/metering.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { meteringRouter } from '../src/trpc/routers/metering.router';
import type { AuthUser } from '../src/trpc/auth-user';
import type { Context } from '../src/trpc/trpc';

const prisma = new PrismaService();
const billing = new BillingService(prisma, new LedgerService(), new NumberService(), new EventEmitter2(), new ApprovalService(prisma));
const metering = new MeteringService(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); }
}

/** The office's own door onto the meters, so the refusals below are the ones a
 *  clerk would actually meet. */
function staffCtx(orgId: string): Context {
  const user: AuthUser = {
    id: 'zz-decl-staff', email: 'zz-decl-staff@zz.test', name: 'ZZ Decl Staff', tenantId: null, mustChangePassword: false,
    roles: ['ADMIN'], permissions: ['meter-reading.read', 'meter-reading.create', 'meter-reading.update', 'meter-reading.delete'],
  };
  return { prisma, user, organizationId: orgId, metering } as unknown as Context;
}

const created: { invoiceIds: string[] } = { invoiceIds: [] };
const powerLines = async (invoiceId: string) =>
  (await prisma.invoiceLine.findMany({ where: { invoiceId }, select: { description: true, amount: true } })).filter((l) => l.description.includes('ZZ Volt'));

async function main() {
  const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true } });
  if (!org) throw new Error('no org');
  const orgId = org.id;
  const rentCt = await prisma.chargeType.findFirst({ where: { organizationId: orgId, category: 'RECURRING', glAccountId: { not: null }, isActive: true }, select: { id: true } });
  if (!rentCt) throw new Error('no rent charge type');

  await purgeStale();

  const util = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'ZZVOLT', nameEn: 'ZZ Volt', category: 'UTILITY', isActive: true, sortOrder: 999 } });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Decl Tenant' } });
  const property = await prisma.property.create({ data: { organizationId: orgId, name: 'ZZ Decl Property', units: { create: [{ name: 'ZZ V1' }] } }, include: { units: true } });
  await prisma.utilityTariff.create({ data: { chargeTypeId: util.id, propertyId: property.id, unitRate: '2', fixedCharge: '0' } });
  const unit = property.units[0];
  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `ZZ-DECL-${property.id.slice(-5)}`, tenantId: tenant.id,
      status: 'ACTIVE', currency: 'HKD', startDate: new Date('2019-01-01'), endDate: new Date('2100-01-01'), depositMonths: 0,
      units: { create: { unitId: unit.id } },
      chargeRules: { create: [
        { chargeTypeId: rentCt.id, amount: '8000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 },
        { chargeTypeId: util.id, amount: '0', frequencyMonths: 1, timing: 'ARREARS', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 1 },
      ] },
    },
  });
  const meter = await prisma.meter.create({ data: { chargeTypeId: util.id, serialNo: 'ZZ-VOLT-1', units: { create: { unitId: unit.id } } } });
  const tenantUser = await prisma.user.create({ data: { email: 'zz-decl@zz.test', name: 'ZZ Decl', passwordHash: 'x', tenantId: tenant.id } });
  console.log('Fixture: a meter in the tenant’s own flat, rate 2/unit\n');

  const draft = async (period: string) => {
    const inv = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period });
    created.invoiceIds.push(inv.id);
    return inv.id;
  };

  console.log('A. What the office enters is billable at once');
  const staffReading = await metering.createReading({ organizationId: orgId, meterId: meter.id, readingStart: '0', readingEnd: '100', periodStart: '2019-12-01', periodEnd: '2019-12-31' });
  const staffRow = await prisma.meterReading.findUniqueOrThrow({ where: { id: staffReading.id }, select: { status: true, grossAmount: true } });
  ck('A1 a staff reading arrives CONFIRMED', staffRow.status === 'CONFIRMED', `got ${staffRow.status}`);
  ck('A2 and priced (100 × 2)', staffRow.grossAmount?.toFixed(2) === '200.00', `got ${staffRow.grossAmount}`);
  ck('A3 it bills', (await powerLines(await draft('2020-01'))).length === 1);

  console.log('\nB. What a tenant declares arrives pending and unpriced');
  const declared = await prisma.meterReading.create({
    data: { meterId: meter.id, readingStart: '100', readingEnd: '250', periodStart: new Date('2020-01-01'), periodEnd: new Date('2020-01-31'), status: 'PENDING', submittedByUserId: tenantUser.id },
  });
  const decl = await prisma.meterReading.findUniqueOrThrow({ where: { id: declared.id }, select: { status: true, grossAmount: true } });
  ck('B1 it is PENDING', decl.status === 'PENDING');
  ck('B2 and carries no amount yet', decl.grossAmount === null, `got ${decl.grossAmount}`);

  console.log('\nC. A declaration cannot reach a debit note before it is checked');
  ck('C1 the note skips it', (await powerLines(await draft('2020-02'))).length === 0);
  const stillPending = await prisma.meterReading.findUniqueOrThrow({ where: { id: declared.id }, select: { _count: { select: { claims: true } } } });
  ck('C2 and does not consume it', stillPending._count.claims === 0);

  console.log('\nD. Confirming prices it and lets it through');
  await metering.updateReading({ organizationId: orgId, id: declared.id, readingStart: '100', readingEnd: '250', periodStart: '2020-01-01', periodEnd: '2020-01-31' });
  await prisma.meterReading.update({ where: { id: declared.id }, data: { status: 'CONFIRMED' } });
  const confirmed = await prisma.meterReading.findUniqueOrThrow({ where: { id: declared.id }, select: { grossAmount: true } });
  ck('D1 it is priced on confirmation (150 × 2)', confirmed.grossAmount?.toFixed(2) === '300.00', `got ${confirmed.grossAmount}`);
  const after = await powerLines(await draft('2020-03'));
  ck('D2 the next note bills it', after.length === 1 && after[0].amount.toString() === '300', `got ${after.map((l) => l.amount)}`);

  console.log('\nE. A rejected declaration never bills');
  const bad = await prisma.meterReading.create({
    data: { meterId: meter.id, readingStart: '250', readingEnd: '9999', periodStart: new Date('2020-02-01'), periodEnd: new Date('2020-02-29'), status: 'REJECTED', submittedByUserId: tenantUser.id, rejectionReason: '相片同數字對唔上' },
  });
  ck('E1 the note skips it', (await powerLines(await draft('2020-04'))).length === 0);
  const rejected = await prisma.meterReading.findUniqueOrThrow({ where: { id: bad.id }, select: { rejectionReason: true, _count: { select: { claims: true } } } });
  ck('E2 the reason is kept for the tenant', rejected.rejectionReason === '相片同數字對唔上');
  ck('E3 and it is not consumed', rejected._count.claims === 0);

  const meters = meteringRouter.createCaller(staffCtx(orgId));

  console.log('\nF. A reading already on a note cannot be edited underneath it');
  // The note's amount was frozen at billing, but the evidence page printed behind
  // it re-reads the reading live — so a corrected dial would go out beside a
  // charge computed from the old one.
  const onNote = await prisma.meterReading.findUniqueOrThrow({ where: { id: staffReading.id }, select: { _count: { select: { claims: true } } } });
  ck('F1 December’s reading did go out on a note', onNote._count.claims > 0, `got ${onNote._count.claims} claim(s)`);
  const edit = await refused(() => meters.updateReading({ id: staffReading.id, readingStart: '0', readingEnd: '105', periodStart: '2019-12-01', periodEnd: '2019-12-31' }));
  ck('F2 editing it is refused, as deleting it already was', edit.includes('already billed on a debit note'), `got "${edit}"`);
  const untouched = await prisma.meterReading.findUniqueOrThrow({ where: { id: staffReading.id }, select: { readingEnd: true, grossAmount: true } });
  ck('F3 and neither the dial nor the amount moved', Number(untouched.readingEnd) === 100 && untouched.grossAmount?.toFixed(2) === '200.00', `got ${untouched.readingEnd} / ${untouched.grossAmount}`);
  // An unbilled one is still the ordinary correction it always was.
  const loose = await metering.createReading({ organizationId: orgId, meterId: meter.id, readingStart: '300', readingEnd: '320', periodStart: '2020-05-01', periodEnd: '2020-05-31' });
  await meters.updateReading({ id: loose.id, readingStart: '300', readingEnd: '330', periodStart: '2020-05-01', periodEnd: '2020-05-31' });
  const corrected = await prisma.meterReading.findUniqueOrThrow({ where: { id: loose.id }, select: { readingEnd: true, grossAmount: true } });
  ck('F4 an unbilled reading still corrects, and re-prices (30 × 2)', Number(corrected.readingEnd) === 330 && corrected.grossAmount?.toFixed(2) === '60.00', `got ${corrected.readingEnd} / ${corrected.grossAmount}`);

  console.log('\nG. Confirming a declaration still goes through that same door');
  // confirmReading corrects the figures through updateReading — the very call F
  // refuses — so the refusal must not reach a declaration awaiting review.
  const awaiting = await prisma.meterReading.create({
    data: { meterId: meter.id, readingStart: '330', readingEnd: '400', periodStart: new Date('2020-06-01'), periodEnd: new Date('2020-06-30'), status: 'PENDING', submittedByUserId: tenantUser.id },
  });
  const confirmFailed = await refused(() => meters.confirmReading({ id: awaiting.id, readingEnd: '370' }));
  ck('G1 confirming is not refused', confirmFailed === '', `got "${confirmFailed}"`);
  const accepted = await prisma.meterReading.findUniqueOrThrow({ where: { id: awaiting.id }, select: { status: true, readingEnd: true, grossAmount: true } });
  ck('G2 it is CONFIRMED, with the checked figure', accepted.status === 'CONFIRMED' && Number(accepted.readingEnd) === 370, `got ${accepted.status} / ${accepted.readingEnd}`);
  ck('G3 and priced from it (40 × 2)', accepted.grossAmount?.toFixed(2) === '80.00', `got ${accepted.grossAmount}`);

  console.log('\nH. The next reading opens from a CONFIRMED figure, nothing else');
  const fresh = await prisma.meter.create({ data: { chargeTypeId: util.id, serialNo: 'ZZ-VOLT-2', units: { create: { unitId: unit.id } } } });
  ck('H1 a meter never read offers no starting point', (await meters.lastReading({ meterId: fresh.id })) === null);
  await metering.createReading({ organizationId: orgId, meterId: fresh.id, readingStart: '0', readingEnd: '10', periodStart: '2021-01-01', periodEnd: '2021-01-31' });
  const afterStaff = await meters.lastReading({ meterId: fresh.id });
  ck('H2 a confirmed reading is one', Number(afterStaff?.readingEnd) === 10 && afterStaff?.periodEnd.toISOString().slice(0, 10) === '2021-01-31', JSON.stringify(afterStaff));
  // Later than the confirmed one on both dates, so only the status keeps it out.
  const waiting = await prisma.meterReading.create({
    data: { meterId: fresh.id, readingStart: '10', readingEnd: '60', periodStart: new Date('2021-02-01'), periodEnd: new Date('2021-02-28'), status: 'PENDING', submittedByUserId: tenantUser.id },
  });
  const afterPending = await meters.lastReading({ meterId: fresh.id });
  ck('H3 a declaration still awaiting review is not', Number(afterPending?.readingEnd) === 10, JSON.stringify(afterPending));
  await prisma.meterReading.create({
    data: { meterId: fresh.id, readingStart: '10', readingEnd: '9999', periodStart: new Date('2021-03-01'), periodEnd: new Date('2021-03-31'), status: 'REJECTED', submittedByUserId: tenantUser.id, rejectionReason: '睇錯錶' },
  });
  const afterRejected = await meters.lastReading({ meterId: fresh.id });
  ck('H4 nor is one that was sent back', Number(afterRejected?.readingEnd) === 10 && afterRejected?.periodEnd.toISOString().slice(0, 10) === '2021-01-31', JSON.stringify(afterRejected));

  console.log('\nI. The same days can never be confirmed twice on one meter');
  // Opening from the confirmed figure means the office can walk out and read a
  // dial across days a declaration already claims. Nothing downstream would
  // notice — billing makes a line of every confirmed reading — so the second one
  // is refused here instead.
  const over = await refused(() => meters.createReading({ meterId: fresh.id, readingStart: '5', readingEnd: '40', periodStart: '2021-01-15', periodEnd: '2021-02-10' }));
  ck('I1 a reading across days already confirmed is refused', over.includes('already has a confirmed reading'), `got "${over}"`);
  // Chaining is not overlapping: this one starts on the day the other ended.
  const chained = await refused(() => meters.createReading({ meterId: fresh.id, readingStart: '10', readingEnd: '75', periodStart: '2021-01-31', periodEnd: '2021-04-30' }));
  ck('I2 one that starts where the last ended is not', chained === '', `got "${chained}"`);
  // It covers February, which the tenant's declaration also covers — allowed,
  // because a declaration bills nothing. The gate is on the way to CONFIRMED.
  const confirmOver = await refused(() => meters.confirmReading({ id: waiting.id }));
  ck('I3 confirming the declaration it overtook is refused', confirmOver.includes('already has a confirmed reading'), `got "${confirmOver}"`);
  const stillWaiting = await prisma.meterReading.findUniqueOrThrow({ where: { id: waiting.id }, select: { status: true, grossAmount: true } });
  ck('I4 and it is left awaiting review, unpriced', stillWaiting.status === 'PENDING' && stillWaiting.grossAmount === null, `got ${stillWaiting.status} / ${stillWaiting.grossAmount}`);
  await meters.rejectReading({ id: waiting.id, reason: 'office read the dial itself' });
  const billable = await prisma.meterReading.count({ where: { meterId: fresh.id, status: 'CONFIRMED' } });
  ck('I5 sending it back still works, leaving one billable reading per stretch', billable === 2, `got ${billable}`);
}

async function purgeStale() {
  await prisma.user.deleteMany({ where: { email: 'zz-decl@zz.test' } });
  const meters = await prisma.meter.findMany({ where: { serialNo: { startsWith: 'ZZ-VOLT-' } }, select: { id: true } });
  const mids = meters.map((m) => m.id);
  if (mids.length) {
    await prisma.meterReading.deleteMany({ where: { meterId: { in: mids } } });
    await prisma.meterUnit.deleteMany({ where: { meterId: { in: mids } } });
    await prisma.meter.deleteMany({ where: { id: { in: mids } } });
  }
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: 'ZZ-DECL' } }, select: { id: true } });
  for (const l of leases) {
    const ids = (await prisma.invoice.findMany({ where: { leaseId: l.id }, select: { id: true } })).map((i) => i.id);
    if (ids.length) {
      const entries = await prisma.journalEntry.findMany({ where: { OR: [{ sourceId: { in: ids } }, { lines: { some: { invoiceId: { in: ids } } } }] }, select: { id: true } });
      const eids = entries.map((e) => e.id);
      if (eids.length) {
        await prisma.journalLine.deleteMany({ where: { entryId: { in: eids } } });
        await prisma.journalEntry.deleteMany({ where: { id: { in: eids } } });
      }
      await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: ids } } });
      await prisma.invoice.deleteMany({ where: { id: { in: ids } } });
    }
    await prisma.leaseUnit.deleteMany({ where: { leaseId: l.id } });
    await prisma.chargeRule.deleteMany({ where: { leaseId: l.id } });
    await prisma.lease.delete({ where: { id: l.id } }).catch(() => {});
  }
  const props = await prisma.property.findMany({ where: { name: 'ZZ Decl Property' }, select: { id: true, units: { select: { id: true } } } });
  for (const p of props) {
    await prisma.unit.deleteMany({ where: { id: { in: p.units.map((u) => u.id) } } });
    await prisma.property.delete({ where: { id: p.id } }).catch(() => {});
  }
  await prisma.tenant.deleteMany({ where: { name: 'ZZ Decl Tenant' } });
  const ct = await prisma.chargeType.findFirst({ where: { code: 'ZZVOLT' }, select: { id: true } });
  if (ct) {
    await prisma.utilityTariff.deleteMany({ where: { chargeTypeId: ct.id } });
    await prisma.chargeType.delete({ where: { id: ct.id } }).catch(() => {});
  }
}

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

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