/**
 * Functional smoke: the repair slips and receipts behind a maintenance request,
 * and the leases a request is offered.
 *
 * The office charges a tenant-borne repair onto the tenant's debit note, and
 * wants the proof — the repair slip, the bank-in or supplier receipt — to go
 * with it. Nothing blocks a charge without proof; the files simply travel when
 * they are there.
 *
 * What this proves against the real router, services and renderer:
 *   · the lease picker knows each lease's units and its tenant's code with the
 *     lease's landlord company, so it can narrow to a unit and name the tenant;
 *   · a file on a request must name a type from the maintenance list — not the
 *     property paperwork list;
 *   · the request reads back its files with their type, and the option list
 *     counts them as in use;
 *   · charging copies them onto the charge line, each with its own stored file
 *     and its type as the caption, so deleting the request's file leaves the
 *     note's whole;
 *   · the note names the photo and the PDF together on one supporting page,
 *     and the PDF's own pages follow the note.
 *
 * Standalone, self-cleaning: its own ZZ organisation, purged at each end.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/maintenance-evidence-smoke.ts
 */
import 'reflect-metadata';
import { ConfigService } from '@nestjs/config';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { PDFDocument } from 'pdf-lib';
import { AttachmentService } from '../src/attachments/attachment.service';
import { StorageService } from '../src/attachments/storage.service';
import { DocumentService } from '../src/documents/document.service';
import { PdfService } from '../src/documents/pdf.service';
import { MaintenanceService } from '../src/maintenance/maintenance.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { maintenanceRouter } from '../src/trpc/routers/maintenance.router';
import { referenceValuesRouter } from '../src/trpc/routers/reference-values.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 attachments = new AttachmentService(prisma, storage);
const maintenance = new MaintenanceService(prisma, new EventEmitter2(), storage);
const pdf = new PdfService(config);
const documents = new DocumentService(prisma, storage, pdf);

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-MEV-ORG';
// A 1×1 PNG: the smallest real image the renderer will inline.
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');

const staff: AuthUser = {
  id: 'zz-mev-staff', email: 'zz-mev@rms.local', name: 'ZZ MEV Staff', tenantId: null, mustChangePassword: false,
  roles: ['ADMIN'],
  permissions: ['maintenance.read', 'maintenance.create', 'maintenance.update', 'invoice.read', 'invoice.update', 'reference-value.read'],
};
const ctxOf = (orgId: string): Context => ({ prisma, user: staff, organizationId: orgId, maintenance } as unknown as Context);

async function purge() {
  const org = await prisma.organization.findUnique({ where: { code: ORG_CODE }, select: { id: true } });
  if (!org) return;
  const files = await prisma.attachment.findMany({ where: { organizationId: org.id }, select: { storageKey: true } });
  for (const f of files) await storage.remove(f.storageKey).catch(() => undefined);
  await prisma.attachment.deleteMany({ where: { organizationId: org.id } });
  await prisma.maintenanceRequest.deleteMany({ where: { organizationId: org.id } });
  const invoices = await prisma.invoice.findMany({ where: { organizationId: org.id }, select: { id: true } });
  await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invoices.map((i) => i.id) } } });
  await prisma.invoice.deleteMany({ where: { organizationId: org.id } });
  await prisma.lease.deleteMany({ where: { organizationId: org.id } }); // lease units and rules cascade
  const props = await prisma.property.findMany({ where: { organizationId: org.id }, select: { id: true } });
  await prisma.unit.deleteMany({ where: { propertyId: { in: props.map((p) => p.id) } } });
  await prisma.property.deleteMany({ where: { organizationId: org.id } });
  await prisma.tenantCode.deleteMany({ where: { organizationId: org.id } });
  await prisma.tenant.deleteMany({ where: { organizationId: org.id } });
  await prisma.landlord.deleteMany({ where: { organizationId: org.id } });
  await prisma.referenceValue.deleteMany({ where: { organizationId: org.id } });
  await prisma.chargeType.deleteMany({ where: { organizationId: org.id } });
  await prisma.glAccount.deleteMany({ where: { organizationId: org.id } });
  await prisma.organization.delete({ where: { id: org.id } });
}

async function main() {
  await purge();
  const org = await prisma.organization.create({ data: { code: ORG_CODE, name: 'ZZ Maintenance Evidence Org' } });
  const orgId = org.id;
  const expense = await prisma.glAccount.create({ data: { organizationId: orgId, code: '6000', name: 'Repairs', type: 'EXPENSE' } });
  await prisma.chargeType.create({ data: { organizationId: orgId, code: 'RM', nameEn: 'Repairs & Maintenance', category: 'ONE_OFF', glAccountId: expense.id } });
  const [slip, receipt, deed] = await Promise.all([
    prisma.referenceValue.create({ data: { organizationId: orgId, domain: 'MAINTENANCE_DOCUMENT_TYPE', code: 'REPAIR_SLIP', nameEn: 'Repair Slip', nameZh: '維修單' } }),
    prisma.referenceValue.create({ data: { organizationId: orgId, domain: 'MAINTENANCE_DOCUMENT_TYPE', code: 'SUPPLIER_RECEIPT', nameEn: 'Supplier Receipt', nameZh: '供應商收據' } }),
    prisma.referenceValue.create({ data: { organizationId: orgId, domain: 'PROPERTY_DOCUMENT_TYPE', code: 'TITLE_DEEDS', nameEn: 'Title Deeds' } }),
  ]);
  const landlord = await prisma.landlord.create({ data: { organizationId: orgId, code: 'ZW', name: 'ZZ Well Faith Limited' } });
  const property = await prisma.property.create({
    data: { organizationId: orgId, name: 'ZZ MEV Plaza', landlordId: landlord.id, units: { create: [{ name: '611' }, { name: 'L10 車位' }] } },
    include: { units: true },
  });
  const [office, carSpace] = ['611', 'L10 車位'].map((n) => property.units.find((u) => u.name === n)!);
  const coder = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Arthur Communications Limited' } });
  await prisma.tenantCode.create({ data: { organizationId: orgId, tenantId: coder.id, landlordId: landlord.id, code: 'ZWARTH01' } });
  const other = await prisma.tenant.create({ data: { organizationId: orgId, name: 'ZZ Oriental Inc' } });
  const mkLease = (reference: string, tenantId: string, unitId: string) =>
    prisma.lease.create({
      data: { organizationId: orgId, reference, tenantId, status: 'ACTIVE', currency: 'HKD', startDate: new Date('2026-01-01'), endDate: new Date('2027-12-31'), units: { create: { unitId } } },
    });
  const officeLease = await mkLease('ZZ-MEV-L1', coder.id, office.id);
  const carLease = await mkLease('ZZ-MEV-L2', other.id, carSpace.id);
  const router = maintenanceRouter.createCaller(ctxOf(orgId));

  console.log('A. The lease picker');
  const fd = await router.formData();
  const l1 = fd.leases.find((l) => l.id === officeLease.id);
  const l2 = fd.leases.find((l) => l.id === carLease.id);
  ck('A1 each lease names its tenant, and the code with its landlord company', l1?.tenantName === coder.name && l1?.tenantCode === 'ZWARTH01', JSON.stringify(l1));
  ck('A2 a tenant with no code there has none', l2?.tenantCode === null);
  ck('A3 and each knows its units, so the form can narrow to the car space’s lease',
    fd.leases.filter((l) => l.unitIds.includes(carSpace.id)).map((l) => l.id).join() === carLease.id);
  ck('A4 the maintenance document types are offered, not the property ones',
    fd.documentTypes.some((t) => t.id === slip.id) && !fd.documentTypes.some((t) => t.id === deed.id));

  console.log('\nB. Filing the proof');
  const req = await maintenance.create({
    organizationId: orgId, propertyId: property.id, unitId: office.id, leaseId: officeLease.id, tenantId: coder.id,
    title: 'Air conditioning', costResponsibility: 'TENANT', reportedByUserId: staff.id,
  });
  const file = (filename: string, mimeType: string, buffer: Buffer, documentTypeId?: string, caption?: string) =>
    attachments.upload({ user: staff, organizationId: orgId, ownerType: 'MAINTENANCE_REQUEST', ownerId: req.id, filename, mimeType, buffer, documentTypeId, caption });
  const untyped = await refused(() => file('slip.png', 'image/png', PNG));
  ck('B1 a file must say what kind it is', untyped === 'Choose what kind of document this is', `got "${untyped}"`);
  const wrongList = await refused(() => file('slip.png', 'image/png', PNG, deed.id));
  ck('B2 from the maintenance list, not the property paperwork', wrongList === 'Document type not found', `got "${wrongList}"`);
  const doc = await PDFDocument.create();
  doc.addPage();
  doc.addPage();
  const slipFile = await file('repair-slip.png', 'image/png', PNG, slip.id);
  const receiptFile = await file('supplier-receipt.pdf', 'application/pdf', Buffer.from(await doc.save()), receipt.id, 'Invoice 123');
  const got = await router.get({ id: req.id });
  ck('B3 the request reads its files back with their type',
    got?.attachments.length === 2 && got.attachments[0].typeNameZh === '維修單' && got.attachments[1].caption === 'Invoice 123', JSON.stringify(got?.attachments));
  const listed = await referenceValuesRouter.createCaller(ctxOf(orgId)).list();
  ck('B4 the option list counts each type as in use', listed.find((v) => v.id === slip.id)?.usageCount === 1 && listed.find((v) => v.id === receipt.id)?.usageCount === 1);

  console.log('\nC. Charged to the tenant, the proof goes with it');
  await prisma.maintenanceRequest.update({ where: { id: req.id }, data: { status: 'COMPLETED', actualCost: '1800' } });
  const { invoiceId } = await maintenance.chargeToTenant({ organizationId: orgId, id: req.id });
  const line = await prisma.invoiceLine.findFirstOrThrow({ where: { invoiceId } });
  const carried = await prisma.attachment.findMany({ where: { ownerType: 'INVOICE_LINE', ownerId: line.id }, orderBy: { createdAt: 'asc' } });
  ck('C1 both files are on the charge line', carried.length === 2, `${carried.length}`);
  ck('C2 each with its own stored file', carried.every((c) => ![slipFile.storageKey, receiptFile.storageKey].includes(c.storageKey)));
  ck('C3 named by their type on the note', carried[0]?.caption === 'Repair Slip' && carried[1]?.caption === 'Supplier Receipt — Invoice 123', JSON.stringify(carried.map((c) => c.caption)));
  await attachments.remove(staff, orgId, slipFile.id);
  ck('C4 deleting the request’s file leaves the note’s whole', (await storage.read(carried[0].storageKey)).equals(PNG));
  const { html, appendPdfs } = await documents.invoiceHtml(orgId, invoiceId);
  ck('C5 the note prints them as supporting documents, without the office file name',
    html.includes('Supporting documents') && html.includes('Maintenance: Air conditioning') && !html.includes('repair-slip.png') && !html.includes('supplier-receipt.pdf'));
  ck('C6 the photo is on that page and the PDF’s own pages still follow',
    appendPdfs.some((a) => a.id === carried[1].id) && html.includes('data:image/png;base64,') && !html.includes('its pages follow'));
  const renderer = pdf.rendererStatus();
  if (!renderer.ok) {
    console.log(`  — C7 skipped: no PDF renderer here (${renderer.source}: ${renderer.detail ?? ''})`);
  } else {
    const bytes = await documents.invoicePdf(orgId, invoiceId);
    const pages = (await PDFDocument.load(bytes)).getPageCount();
    ck('C7 the PDF’s two pages follow the note and its evidence', pages >= 4, `${pages} pages`);
  }
}

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