/**
 * Functional smoke: the notice / letter log.
 *
 * The office's spreadsheet keeps a correspondence tab — Date | Type | Remark —
 * next to fees marked "subject to change with notice". The system had nowhere
 * for it, so the notice a fee increase depended on existed only in a filing
 * cabinet.
 *
 * What this proves against the real routers and the real attachment service:
 *   · the Type list is an ordinary reference list the office maintains itself,
 *     and the option-list editor counts how many letters use each value;
 *   · an entry may name one tenancy and the standard charge it announced, and
 *     both links are refused when they belong to another building;
 *   · recording a fee change and the letter that announced it in ONE save;
 *   · a scanned letter attaches, downloads and is deleted with its entry;
 *   · a TENANT reaches none of it — not the router, not the file, not even for
 *     a letter about their own tenancy;
 *   · each action needs its own permission, and another organisation sees
 *     nothing at all.
 *
 * Standalone, self-cleaning: its own ZZ organisation and its own storage root,
 * both purged at each end.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/notice-log-smoke.ts
 */
import 'reflect-metadata';
import { ConfigService } from '@nestjs/config';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { AttachmentService } from '../src/attachments/attachment.service';
import { StorageService } from '../src/attachments/storage.service';
import { PrismaService } from '../src/prisma/prisma.service';
import { noticesRouter } from '../src/trpc/routers/notices.router';
import { portalRouter } from '../src/trpc/routers/portal.router';
import { referenceValuesRouter } from '../src/trpc/routers/reference-values.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';

// Its own storage root, so an uploaded fixture can never land next to the
// office's real files. Set before StorageService reads the config.
const STORAGE_ROOT = mkdtempSync(join(tmpdir(), 'zz-notice-'));
process.env.STORAGE_LOCAL_ROOT = STORAGE_ROOT;

const prisma = new PrismaService();
const attachments = new AttachmentService(prisma, new StorageService(new ConfigService()));

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 PFX = 'ZZ-NT';
const ORG_CODE = `${PFX}-ORG`;
const OTHER_ORG_CODE = `${PFX}-ORG2`;
const FULL = [
  'notice.read', 'notice.create', 'notice.update', 'notice.delete',
  'property.read', 'property.update', 'lease.read',
  'reference-value.read', 'reference-value.create', 'reference-value.update',
];

const staffUser = (permissions: string[]): AuthUser => ({
  id: 'zz-nt-staff', email: 'zz-nt@rms.local', name: 'ZZ NT', tenantId: null, mustChangePassword: false, roles: ['ADMIN'], permissions,
});
const tenantUser = (tenantId: string): AuthUser => ({
  id: 'zz-nt-tenant', email: 'zz-nt-t@rms.local', name: 'ZZ NT Tenant', tenantId, mustChangePassword: false, roles: ['TENANT'], permissions: [],
});
const ctxOf = (orgId: string, user: AuthUser): Context => ({ prisma, user, organizationId: orgId } as unknown as Context);

/** A one-pixel PNG. Only the declared mime type is checked; the bytes just have
 *  to survive the round trip. */
const PNG = Buffer.from(
  'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
  'base64',
);

async function purgeOrg(code: string) {
  const org = await prisma.organization.findUnique({ where: { code }, select: { id: true } });
  if (!org) return;
  const notices = await prisma.propertyNotice.findMany({ where: { organizationId: org.id }, select: { id: true } });
  const files = await prisma.attachment.findMany({
    where: { organizationId: org.id, ownerType: 'PROPERTY_NOTICE', ownerId: { in: notices.map((n) => n.id) } },
    select: { id: true },
  });
  for (const f of files) await prisma.attachment.delete({ where: { id: f.id } });
  await prisma.propertyNotice.deleteMany({ where: { organizationId: org.id } });
  await prisma.standardCharge.deleteMany({ where: { organizationId: org.id } });
  const leases = await prisma.lease.findMany({ where: { organizationId: org.id }, select: { id: true } });
  const leaseIds = leases.map((l) => l.id);
  if (leaseIds.length) {
    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: { organizationId: org.id }, select: { id: true } });
  await prisma.unit.deleteMany({ where: { propertyId: { in: props.map((p) => p.id) } } });
  await prisma.property.deleteMany({ where: { id: { in: props.map((p) => p.id) } } });
  await prisma.tenant.deleteMany({ where: { organizationId: org.id } });
  await prisma.chargeType.deleteMany({ where: { organizationId: org.id } });
  await prisma.glAccount.deleteMany({ where: { organizationId: org.id } });
  await prisma.referenceValue.deleteMany({ where: { organizationId: org.id } });
  await prisma.organization.delete({ where: { id: org.id } });
}
const purge = async () => { await purgeOrg(ORG_CODE); await purgeOrg(OTHER_ORG_CODE); };

async function main() {
  await purge();
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'Notice log smoke org' } })).id;
  const notices = noticesRouter.createCaller(ctxOf(orgId, staffUser(FULL)));
  const sc = standardChargesRouter.createCaller(ctxOf(orgId, staffUser(FULL)));
  const refs = referenceValuesRouter.createCaller(ctxOf(orgId, staffUser(FULL)));

  const gl = await prisma.glAccount.create({ data: { organizationId: orgId, code: '4100', name: 'Mgmt Fee Income', type: 'INCOME' } });
  const mgmtCt = await prisma.chargeType.create({ data: { organizationId: orgId, code: 'MGMT_FEE', nameEn: 'Management Fee', category: 'RECURRING', glAccountId: gl.id } });
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: `${PFX} Tenant` } });
  const propA = await prisma.property.create({ data: { organizationId: orgId, name: `${PFX} Tower A`, units: { create: [{ name: 'A1' }] } } });
  const propB = await prisma.property.create({ data: { organizationId: orgId, name: `${PFX} Tower B`, units: { create: [{ name: 'B1' }] } } });
  const unitA = await prisma.unit.findFirstOrThrow({ where: { propertyId: propA.id } });
  const leaseA = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `${PFX}-LA`, tenantId: tenant.id, status: 'ACTIVE',
      startDate: new Date('2026-01-01T00:00:00.000Z'), endDate: new Date('2027-12-31T00:00:00.000Z'),
      units: { create: { unitId: unitA.id } },
    },
  });
  const leaseB = await prisma.lease.create({
    data: {
      organizationId: orgId, reference: `${PFX}-LB`, tenantId: tenant.id, status: 'ACTIVE',
      startDate: new Date('2026-01-01T00:00:00.000Z'), endDate: new Date('2027-12-31T00:00:00.000Z'),
    },
  });

  console.log('A. The Type list is an ordinary reference list the office maintains');
  const tAdj = await refs.create({ domain: 'NOTICE_TYPE', code: 'ZZ_MGMT_ADJ', nameEn: 'ZZ Management Fee Adjustment', nameZh: '管理費調整', sortOrder: 900, isActive: true });
  const tOther = await refs.create({ domain: 'NOTICE_TYPE', code: 'ZZ_OTHERS', nameEn: 'ZZ Others', nameZh: '其他', sortOrder: 901, isActive: true });
  ck('A1 a notice type can be added from the option-list editor', Boolean(tAdj.id) && Boolean(tOther.id));
  const form = await notices.formData();
  ck('A2 and both are offered on the notice form', form.types.some((t) => t.id === tAdj.id) && form.types.some((t) => t.id === tOther.id));
  ck('A3 the form offers this org’s properties and its live tenancies',
    form.properties.length === 2 && form.leases.some((l) => l.id === leaseA.id && l.propertyIds.includes(propA.id) && l.tenantName === `${PFX} Tenant`));

  console.log('\nB. Recording letters');
  const n1 = await notices.create({ propertyId: propA.id, date: '2026-06-03', typeId: tAdj.id, remark: 'Management fee to rise to 600 from 1 July. Posted to all units.' });
  const n2 = await notices.create({ propertyId: propA.id, date: '2026-06-10', typeId: tOther.id, remark: 'Lift maintenance shutdown, 2nd floor.', leaseId: leaseA.id });
  ck('B1 both are stored', Boolean(n1.id) && Boolean(n2.id));
  const list = await notices.list({ propertyId: propA.id });
  ck('B2 the log reads newest first', list.length === 2 && list[0].id === n2.id, JSON.stringify(list.map((r) => r.date)));
  ck('B3 it names the type in both languages', list.find((r) => r.id === n1.id)?.typeNameEn === 'ZZ Management Fee Adjustment' && list.find((r) => r.id === n1.id)?.typeNameZh === '管理費調整');
  ck('B4 a letter sent to one tenancy names it', list.find((r) => r.id === n2.id)?.leaseReference === `${PFX}-LA` && list.find((r) => r.id === n2.id)?.tenantName === `${PFX} Tenant`);
  ck('B5 a building-wide letter names no tenancy', list.find((r) => r.id === n1.id)?.leaseId === null);
  ck('B6 the log can be read for one tenancy', (await notices.list({ leaseId: leaseA.id })).map((r) => r.id).join() === n2.id);
  ck('B7 another building’s log is empty', (await notices.list({ propertyId: propB.id })).length === 0);
  const got = await notices.get({ id: n1.id });
  ck('B8 one entry reads back whole', got.remark.startsWith('Management fee to rise') && got.date === '2026-06-03' && got.propertyName === `${PFX} Tower A`);
  await notices.update({ id: n2.id, propertyId: propA.id, date: '2026-06-11', typeId: tOther.id, remark: 'Lift maintenance shutdown, 2nd and 3rd floors.', leaseId: leaseA.id });
  ck('B9 an entry can be corrected', (await notices.get({ id: n2.id })).remark.endsWith('2nd and 3rd floors.') && (await notices.get({ id: n2.id })).date === '2026-06-11');
  const usage = await refs.list();
  ck('B10 the option-list editor counts the letters filed under each type',
    usage.find((r) => r.id === tAdj.id)?.usageCount === 1 && usage.find((r) => r.id === tOther.id)?.usageCount === 1,
    JSON.stringify(usage.filter((r) => r.domain === 'NOTICE_TYPE').map((r) => `${r.code}=${r.usageCount}`)));

  console.log('\nC. Links that belong to another building are refused');
  const wrongLease = await refused(() => notices.create({ propertyId: propA.id, date: '2026-06-03', typeId: tAdj.id, remark: 'x', leaseId: leaseB.id }));
  ck('C1 a tenancy from another building is refused', wrongLease.includes('not on this property'), `got "${wrongLease}"`);
  const bogusType = await refused(() => notices.create({ propertyId: propA.id, date: '2026-06-03', typeId: 'not-a-type', remark: 'x' }));
  ck('C2 a type id that is not a notice type is refused', bogusType.includes('Notice type not found'), `got "${bogusType}"`);
  const scB = await sc.create({ propertyId: propB.id, chargeTypeId: mgmtCt.id, amount: '800', effectiveFrom: '2026-07-01' });
  const wrongCharge = await refused(() => notices.create({ propertyId: propA.id, date: '2026-06-03', typeId: tAdj.id, remark: 'x', standardChargeId: scB.id }));
  ck('C3 a standard charge from another building is refused', wrongCharge.includes('Standard charge not found'), `got "${wrongCharge}"`);
  ck('C4 none of the three was stored', (await notices.list({ propertyId: propA.id })).length === 2);

  console.log('\nD. The fee change and the letter that announced it, in one save');
  const both = await sc.create({
    propertyId: propA.id, chargeTypeId: mgmtCt.id, amount: '600', effectiveFrom: '2026-07-01',
    notice: { date: '2026-06-03', typeId: tAdj.id, remark: 'Notice of management fee adjustment, 500 → 600.' },
  });
  ck('D1 both rows are created', Boolean(both.id) && Boolean(both.noticeId));
  const announced = (await notices.list({ propertyId: propA.id })).find((r) => r.id === both.noticeId);
  ck('D2 the letter points at the figure it announced',
    announced?.standardChargeId === both.id && announced?.standardCharge?.amount === '600.00' && announced?.standardCharge?.effectiveFrom === '2026-07-01',
    JSON.stringify(announced?.standardCharge));
  ck('D3 …and names the charge it was about', announced?.standardCharge?.chargeTypeNameEn === 'Management Fee');
  // Deleting the figure as a mistake must not shred the correspondence.
  await sc.remove({ id: both.id });
  const orphaned = (await notices.list({ propertyId: propA.id })).find((r) => r.id === both.noticeId);
  ck('D4 deleting the figure leaves the letter, minus the link', Boolean(orphaned) && orphaned?.standardChargeId === null, JSON.stringify(orphaned));

  console.log('\nE. The scanned letter');
  const staffCtx = staffUser(FULL);
  const up = await attachments.upload({
    user: staffCtx, organizationId: orgId, ownerType: 'PROPERTY_NOTICE', ownerId: n1.id,
    filename: 'notice-2026-06-03.png', mimeType: 'image/png', buffer: PNG, caption: 'scan',
  });
  ck('E1 staff can attach it', Boolean(up.id) && up.sizeBytes === PNG.length);
  ck('E2 it shows on the entry', (await notices.get({ id: n1.id })).attachments.some((a) => a.id === up.id));
  ck('E3 and is counted on the log', (await notices.list({ propertyId: propA.id })).find((r) => r.id === n1.id)?.attachments === 1);
  const back = await attachments.getForDownload(staffCtx, orgId, up.id);
  ck('E4 staff can download it back', back.storageKey === up.storageKey && back.filename === 'notice-2026-06-03.png');

  console.log('\nF. A tenant reaches none of it');
  const tenantCaller = noticesRouter.createCaller(ctxOf(orgId, tenantUser(tenant.id)));
  const tenantList = await refused(() => tenantCaller.list());
  ck('F1 the notice router refuses a tenant account outright', tenantList.includes('tenant account and cannot use the back office'), `got "${tenantList}"`);
  const tenantGet = await refused(() => tenantCaller.get({ id: n2.id }));
  ck('F2 …even for the letter about their own tenancy', tenantGet.includes('tenant account and cannot use the back office'), `got "${tenantGet}"`);
  const tenantDownload = await refused(() => attachments.getForDownload(tenantUser(tenant.id), orgId, up.id));
  ck('F3 and the file itself is refused', tenantDownload.includes('Missing permission'), `got "${tenantDownload}"`);
  const tenantUpload = await refused(() => attachments.upload({
    user: tenantUser(tenant.id), organizationId: orgId, ownerType: 'PROPERTY_NOTICE', ownerId: n2.id,
    filename: 'x.png', mimeType: 'image/png', buffer: PNG,
  }));
  ck('F4 a tenant cannot attach one either', tenantUpload.includes('Missing permission'), `got "${tenantUpload}"`);
  const portalProcedures = Object.keys((portalRouter as unknown as { _def: { procedures: Record<string, unknown> } })._def.procedures);
  ck('F5 the tenant portal has no notice procedure at all', !portalProcedures.some((p) => /notice/i.test(p)), portalProcedures.join(','));

  console.log('\nG. Permissions');
  const noRead = noticesRouter.createCaller(ctxOf(orgId, staffUser(['notice.create'])));
  ck('G1 reading the log needs notice.read', (await refused(() => noRead.list())).includes('Missing permission: notice.read'));
  const readOnly = noticesRouter.createCaller(ctxOf(orgId, staffUser(['notice.read'])));
  ck('G2 …which is not enough to file one',
    (await refused(() => readOnly.create({ propertyId: propA.id, date: '2026-07-01', typeId: tAdj.id, remark: 'x' }))).includes('Missing permission: notice.create'));
  ck('G3 nor to correct one',
    (await refused(() => readOnly.update({ id: n1.id, propertyId: propA.id, date: '2026-07-01', typeId: tAdj.id, remark: 'x' }))).includes('Missing permission: notice.update'));
  ck('G4 nor to delete one', (await refused(() => readOnly.remove({ id: n1.id }))).includes('Missing permission: notice.delete'));
  const noFileRead = await refused(() => attachments.getForDownload(staffUser(['notice.create']), orgId, up.id));
  ck('G5 the scan needs notice.read too', noFileRead.includes('Missing permission'), `got "${noFileRead}"`);
  const noFileWrite = await refused(() => attachments.upload({
    user: staffUser(['notice.read']), organizationId: orgId, ownerType: 'PROPERTY_NOTICE', ownerId: n1.id,
    filename: 'x.png', mimeType: 'image/png', buffer: PNG,
  }));
  ck('G6 attaching one needs notice.update', noFileWrite.includes('Missing permission'), `got "${noFileWrite}"`);

  console.log('\nH. Another organisation sees nothing');
  const org2 = (await prisma.organization.create({ data: { code: OTHER_ORG_CODE, name: 'Notice log smoke org 2' } })).id;
  const intruder = noticesRouter.createCaller(ctxOf(org2, staffUser(FULL)));
  ck('H1 the log is empty from over there', (await intruder.list()).length === 0);
  ck('H2 the entry cannot be read by id', (await refused(() => intruder.get({ id: n1.id }))).includes('Notice not found'));
  ck('H3 nor corrected', (await refused(() => intruder.update({ id: n1.id, propertyId: propA.id, date: '2026-07-01', typeId: tAdj.id, remark: 'x' }))).includes('Property not found'));
  ck('H4 nor deleted', (await refused(() => intruder.remove({ id: n1.id }))).includes('Notice not found'));
  ck('H5 nor its scan downloaded', (await refused(() => attachments.getForDownload(staffUser(FULL), org2, up.id))).includes('Attachment not found'));
  ck('H6 the entry is still there', (await notices.get({ id: n1.id })).id === n1.id);

  console.log('\nI. Deleting an entry takes its scan with it');
  await notices.remove({ id: n1.id });
  ck('I1 the entry is gone', (await refused(() => notices.get({ id: n1.id }))).includes('Notice not found'));
  ck('I2 so is the attachment row — nothing points at a deleted owner',
    (await prisma.attachment.count({ where: { ownerType: 'PROPERTY_NOTICE', ownerId: n1.id } })) === 0);
  ck('I3 the other entries are untouched', (await notices.list({ propertyId: propA.id })).length === 2);
}

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 prisma.$disconnect();
    rmSync(STORAGE_ROOT, { recursive: true, force: true });
    console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'} — ${pass} passed, ${fail} failed`);
    process.exit(fail === 0 ? 0 : 1);
  });
