// Asia/Hong_Kong before anything constructs a Date: this is the host timezone a
// naive implementation gets wrong. A date picked in Hong Kong is stored at UTC
// midnight — 08:00 HKT — so comparing it against `new Date()` at a small hour
// says "not yet" all through the chosen day and the note slips by one.
process.env.TZ = 'Asia/Hong_Kong';
/**
 * Functional smoke for deferred issuing. Standalone, self-cleaning.
 *
 * The owner's case: approved on the 25th, goes out on the 28th. Until then
 * nothing has happened — no number, no ledger entry, and nothing the tenant can
 * see. B is the assertion that matters; D is the one that catches the timezone.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/schedule-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 { PrismaService } from '../src/prisma/prisma.service';
import { ISSUED_STATUSES } from '../src/billing/invoice-status';
import { approveInvoice, purgeSmokeApprover } from './_smoke-approval';
import { purgeSmokeLandlord, smokeLandlord } from './_smoke-company';

/** This smoke's own landlord company (see _smoke-company.ts). */
const LANDLORD = 'ZZSCH';

const prisma = new PrismaService();
const approvals = new ApprovalService(prisma);
const billing = new BillingService(prisma, new LedgerService(), new NumberService(), new EventEmitter2(), approvals);
const deps = { prisma, billing, approvals };

let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };
async function expectThrow(name: string, fn: () => Promise<unknown>, contains: string) {
  try { await fn(); ck(name, false, '(expected a throw)'); }
  catch (e) { const m = e instanceof Error ? e.message : String(e); ck(name, m.includes(contains), `wrong message: "${m}"`); }
}

const created: { invoiceIds: string[] } = { invoiceIds: [] };
/** The same token the service compares against: today in Hong Kong, at UTC midnight. */
const hkToday = () => new Date(`${new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Hong_Kong' }).format(new Date())}T00:00:00.000Z`);
const daysFromToday = (n: number) => new Date(hkToday().getTime() + n * 86_400_000);
const invOf = (id: string) =>
  prisma.invoice.findUniqueOrThrow({ where: { id }, select: { status: true, number: true, issueDate: true, scheduledIssueDate: true } });
const entriesFor = (id: string) => prisma.journalEntry.count({ where: { sourceType: 'INVOICE', sourceId: id } });

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 tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Sch Tenant' } });
  const property = await prisma.property.create({ data: { organizationId: orgId, landlordId: await smokeLandlord(prisma, orgId, LANDLORD), name: 'ZZ Sch Property', units: { create: [{ name: 'ZZ S1' }] } }, include: { units: true } });
  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `ZZ-SCH-${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: property.units[0].id } },
      chargeRules: { create: { chargeTypeId: rentCt.id, amount: '9000', frequencyMonths: 1, timing: 'ADVANCE', proration: 'FULL_MONTH', firstInvoiceOnly: false, sortOrder: 0 } },
    },
  });
  /** A note taken to the state a deferred send starts from: approved, unissued. */
  const approved = async (period: string) => {
    const inv = await billing.generateDraft({ organizationId: orgId, leaseId: lease.id, period });
    created.invoiceIds.push(inv.id);
    await approveInvoice(deps, orgId, inv.id);
    return inv.id;
  };
  console.log(`Fixture: rent 9,000. Host TZ=${process.env.TZ}, HK today token = ${hkToday().toISOString()}\n`);

  console.log('A. Scheduling changes nothing else about the note');
  const a = await approved('2099-01');
  const before = await invOf(a);
  await billing.setSchedule({ organizationId: orgId, invoiceId: a, date: daysFromToday(3) });
  const after = await invOf(a);
  ck('A1 the status is untouched', after.status === before.status, `${before.status} → ${after.status}`);
  ck('A2 no number is burned', after.number === null);
  ck('A3 no issue date', after.issueDate === null);
  ck('A4 nothing posted to the ledger', (await entriesFor(a)) === 0);
  ck('A5 the date is recorded', after.scheduledIssueDate?.toISOString() === daysFromToday(3).toISOString(), `got ${after.scheduledIssueDate?.toISOString()}`);
  ck('A6 the tenant still cannot see it', !ISSUED_STATUSES.includes(after.status));

  console.log('\nB. It stays put until the day arrives');
  const run1 = await billing.issueScheduled();
  ck('B1 a future date is not due', (await invOf(a)).status === before.status, `got ${(await invOf(a)).status}`);
  ck('B2 and the run reports nothing due for it', run1.issued === 0 || (await invOf(a)).number === null);

  console.log('\nC. On the day it issues exactly as a human would');
  await billing.setSchedule({ organizationId: orgId, invoiceId: a, date: daysFromToday(1) });
  await prisma.invoice.update({ where: { id: a }, data: { scheduledIssueDate: hkToday() } }); // the day arrives
  const run2 = await billing.issueScheduled();
  const fired = await invOf(a);
  ck('C1 it is ISSUED', fired.status === 'ISSUED', `got ${fired.status}`);
  ck('C2 it has a number', Boolean(fired.number), `got ${fired.number}`);
  ck('C3 the ledger entry is posted', (await entriesFor(a)) === 1);
  ck('C4 the schedule is cleared', fired.scheduledIssueDate === null);
  ck('C5 the run counted it', run2.issued >= 1 && run2.failures.length === 0, JSON.stringify(run2.failures));
  const run3 = await billing.issueScheduled();
  ck('C6 running again does not touch it', (await entriesFor(a)) === 1 && run3.failures.length === 0);

  console.log('\nD. The timezone case: a date set for TODAY in Hong Kong is due today');
  const d = await approved('2099-02');
  await prisma.invoice.update({ where: { id: d }, data: { scheduledIssueDate: hkToday() } });
  // hkToday() is 08:00 HKT — a naive `lte: new Date()` says "not yet" all
  // morning and this note would slip a day. Run it as if the cron fired at 09:00.
  await billing.issueScheduled();
  ck('D1 it goes out on the day, not the day after', (await invOf(d)).status === 'ISSUED', `got ${(await invOf(d)).status}`);

  console.log('\nE. A scheduled note cannot be changed out from under its date');
  // A note is scheduled once it is APPROVED, and an approved note is closed to
  // edits — so what used to be "editing cancels the schedule" is now the
  // stronger guarantee that the figures cannot move at all between the day it
  // is scheduled and the morning it goes out.
  const e = await approved('2099-03');
  await billing.setSchedule({ organizationId: orgId, invoiceId: e, date: daysFromToday(2) });
  let refusedEdit = '';
  try {
    await billing.addAdjustment({ organizationId: orgId, invoiceId: e, chargeTypeId: rentCt.id, description: 'ZZ late change', amount: '100', credit: false });
  } catch (err) {
    refusedEdit = err instanceof Error ? err.message : String(err);
  }
  ck('E1 a late change to an approved, scheduled note is refused', refusedEdit.includes('approved one must be voided'), `got "${refusedEdit}"`);
  ck('E2 so the schedule still stands', (await invOf(e)).scheduledIssueDate !== null);

  // The cron's own guard still matters: a note sitting in approval with a date
  // on it must not go out. Built directly, since no ordinary action reaches it.
  const e2 = await approved('2099-04');
  await prisma.invoice.update({ where: { id: e2 }, data: { status: 'PENDING_APPROVAL', scheduledIssueDate: hkToday() } });
  const runE = await billing.issueScheduled();
  ck('E3 a note in approval is not sent on the day', (await invOf(e2)).status === 'PENDING_APPROVAL', `got ${(await invOf(e2)).status}`);
  // Not reported as a failure either: it is not a candidate at all, so it cannot
  // manufacture the same complaint every morning.
  ck('E4 and it is not reported as a daily failure', !runE.failures.some((x) => x.invoiceId === e2), JSON.stringify(runE.failures));

  console.log('\nF. Issuing by hand takes it out of the queue');
  const f = await approved('2099-04');
  await billing.setSchedule({ organizationId: orgId, invoiceId: f, date: daysFromToday(5) });
  await billing.issue({ organizationId: orgId, invoiceId: f });
  ck('F1 the schedule is cleared with the claim', (await invOf(f)).scheduledIssueDate === null);

  console.log('\nG. Guards');
  const g = await approved('2099-05');
  await expectThrow('G1 a date in the past is refused', () =>
    billing.setSchedule({ organizationId: orgId, invoiceId: g, date: daysFromToday(-1) }), 'after today');
  await expectThrow('G2 so is today — Issue is what sends it now', () =>
    billing.setSchedule({ organizationId: orgId, invoiceId: g, date: hkToday() }), 'after today');
  await expectThrow('G3 an issued note cannot be scheduled', () =>
    billing.setSchedule({ organizationId: orgId, invoiceId: f, date: daysFromToday(3) }), 'unissued');
  await billing.setSchedule({ organizationId: orgId, invoiceId: g, date: daysFromToday(4) });
  await billing.setSchedule({ organizationId: orgId, invoiceId: g, date: null });
  ck('G4 null cancels it', (await invOf(g)).scheduledIssueDate === null);

  console.log('\nH. A voided note is never picked up');
  const h = await approved('2099-06');
  await billing.setSchedule({ organizationId: orgId, invoiceId: h, date: daysFromToday(1) });
  await prisma.invoice.update({ where: { id: h }, data: { scheduledIssueDate: hkToday() } });
  await billing.voidInvoice({ organizationId: orgId, invoiceId: h });
  const runH = await billing.issueScheduled();
  ck('H1 it stays VOID', (await invOf(h)).status === 'VOID');
  ck('H2 and the run does not report it as a failure', !runH.failures.some((x) => x.invoiceId === h));
}

async function purgeStale() {
  const leases = await prisma.lease.findMany({ where: { reference: { startsWith: 'ZZ-SCH' } }, 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, reversesId: true } });
      const eids = entries.map((x) => x.id);
      if (eids.length) {
        await prisma.journalLine.deleteMany({ where: { entryId: { in: eids } } });
        const reversers = entries.filter((x) => x.reversesId).map((x) => x.id);
        if (reversers.length) await prisma.journalEntry.deleteMany({ where: { id: { in: reversers } } });
        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 Sch 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 Sch Tenant' } });
}

async function cleanup() {
  try { await purgeSmokeApprover(prisma); await purgeSmokeLandlord(prisma, LANDLORD); await purgeStale(); 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 prisma.$disconnect(); console.log(`\n==== ${pass} passed, ${fail} failed ====`); process.exit(fail > 0 ? 1 : 0); });
