/**
 * Functional smoke: the paperwork behind a building.
 *
 * The owner's spreadsheet lists, per property, the purchase documents the
 * office has to be able to find — the provisional and formal agreements, the
 * assignment, the land search, the title deeds, the floor plan, the mortgage
 * deed, the apportionment settlement. The system could not attach a file to a
 * property at all: the attachment store served receipts, maintenance, leases,
 * notes, readings and notice letters, and had no owner type for a building.
 *
 * What this proves against the real service, the real router and real bytes:
 *   · upload → list → download round-trips with the bytes intact;
 *   · every file is filed under a document TYPE from an ordinary reference list
 *     the office maintains, and can be re-filed under another later;
 *   · the type CLASSIFIES, it does not supersede — three title deeds on one
 *     building all survive, which is where a `role` would have destroyed two;
 *   · a TENANT reaches none of it, and is refused the same way whether or not
 *     the property exists, so the refusal leaks nothing;
 *   · reading needs property.read and filing needs property.update;
 *   · the wrong file type and an oversized file are refused, and neither leaves
 *     anything on disk;
 *   · a DB write that fails takes the just-written file with it — nothing is
 *     left orphaned in storage;
 *   · another organisation sees nothing, in either direction;
 *   · archiving a building keeps its deeds, because they are the company's
 *     record of what it owns and not of a tenancy.
 *
 * 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/property-document-smoke.ts
 */
import 'reflect-metadata';
import { ConfigService } from '@nestjs/config';
import { mkdtempSync, readdirSync, rmSync, statSync } 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 { portalRouter } from '../src/trpc/routers/portal.router';
import { propertiesRouter } from '../src/trpc/routers/properties.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';

// 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-propdoc-'));
process.env.STORAGE_LOCAL_ROOT = STORAGE_ROOT;

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

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-PD';
const ORG_CODE = `${PFX}-ORG`;
const OTHER_ORG_CODE = `${PFX}-ORG2`;
const STAFF_EMAIL = 'zz-pd-staff@rms.local';
const FULL = ['property.read', 'property.create', 'property.update', 'property.delete', 'reference-value.read', 'reference-value.create'];

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

/** A scanned deed is a PDF in practice; the bytes just have to survive. */
const DEED = Buffer.from('%PDF-1.4\n% ZZ property document fixture\n%%EOF\n', 'utf8');
const PNG = Buffer.from(
  'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
  'base64',
);

/** Everything under the smoke's own storage root — how "nothing was left on
 *  disk" is checked. */
function filesOnDisk(dir = STORAGE_ROOT): string[] {
  let out: string[] = [];
  for (const name of readdirSync(dir)) {
    const p = join(dir, name);
    if (statSync(p).isDirectory()) out = out.concat(filesOnDisk(p));
    else out.push(p);
  }
  return out;
}

const readStored = (key: string): Promise<Buffer> =>
  new Promise((resolve, reject) => {
    const chunks: Buffer[] = [];
    attachments
      .streamKey(key)
      .on('data', (c) => chunks.push(c as Buffer))
      .on('end', () => resolve(Buffer.concat(chunks)))
      .on('error', reject);
  });

async function purgeOrg(code: string) {
  const org = await prisma.organization.findUnique({ where: { code }, select: { id: true } });
  if (!org) return;
  await prisma.attachment.deleteMany({ where: { organizationId: org.id } });
  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.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);
  await prisma.user.deleteMany({ where: { email: STAFF_EMAIL } });
};

async function main() {
  await purge();
  const orgId = (await prisma.organization.create({ data: { code: ORG_CODE, name: 'Property document smoke org' } })).id;
  // A real row, so "who filed this" resolves to a name rather than a null.
  const filer = await prisma.user.create({ data: { email: STAFF_EMAIL, name: 'ZZ PD Staff', passwordHash: 'x' } });
  const staff = staffUser(FULL, filer.id);
  const props = propertiesRouter.createCaller(ctxOf(orgId, staff));
  const refs = referenceValuesRouter.createCaller(ctxOf(orgId, staff));

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: `${PFX} Tenant` } });
  const towerId = (await props.create({ name: `${PFX} Tower`, address: '1 Smoke Road, Kowloon' })).id;
  const shedId = (await props.create({ name: `${PFX} Shed` })).id;

  console.log('A. The document types are an ordinary reference list');
  const deeds = await refs.create({ domain: 'PROPERTY_DOCUMENT_TYPE', code: 'ZZ_TITLE_DEEDS', nameEn: 'ZZ Title Deeds', nameZh: '樓契', sortOrder: 900, isActive: true });
  const mortgage = await refs.create({ domain: 'PROPERTY_DOCUMENT_TYPE', code: 'ZZ_MORTGAGE', nameEn: 'ZZ Mortgage Deed', nameZh: '按揭契', sortOrder: 901, isActive: true });
  const category = await refs.create({ domain: 'PROPERTY_CATEGORY', code: 'ZZ_CAT', nameEn: 'ZZ Category', sortOrder: 902, isActive: true });
  ck('A1 a document type can be added from the option-list editor', Boolean(deeds.id) && Boolean(mortgage.id));
  const form = await props.formData();
  ck('A2 and both are offered on the property form', form.documentTypes.some((t) => t.id === deeds.id) && form.documentTypes.some((t) => t.id === mortgage.id));

  console.log('\nB. Upload → list → download, with the bytes intact');
  const file = (documentTypeId: string, filename: string, caption?: string, buffer = DEED, mimeType = 'application/pdf') =>
    attachments.upload({ user: staff, organizationId: orgId, ownerType: 'PROPERTY', ownerId: towerId, filename, mimeType, buffer, caption, documentTypeId });
  const deed1 = await file(deeds.id, 'title-deed-1997.pdf', 'Original, 1997');
  ck('B1 a deed can be filed against a building', Boolean(deed1.id) && deed1.sizeBytes === DEED.length);
  ck('B2 the type is recorded on it', deed1.documentTypeId === deeds.id);
  const listed = await props.documents({ propertyId: towerId });
  ck('B3 it shows on the property', listed.length === 1 && listed[0].id === deed1.id, JSON.stringify(listed));
  ck('B4 named in both languages', listed[0].typeNameEn === 'ZZ Title Deeds' && listed[0].typeNameZh === '樓契');
  ck('B5 with its caption, size and filer', listed[0].caption === 'Original, 1997' && listed[0].sizeBytes === DEED.length && listed[0].uploadedByName === 'ZZ PD Staff', JSON.stringify(listed[0]));
  const back = await attachments.getForDownload(staff, orgId, deed1.id);
  const bytes = await readStored(back.storageKey);
  ck('B6 the bytes come back exactly as they went in', bytes.equals(DEED), `${bytes.length} vs ${DEED.length}`);
  ck('B7 with the original filename and type', back.filename === 'title-deed-1997.pdf' && back.mimeType === 'application/pdf');

  console.log('\nC. A type classifies; it is not a slot');
  const deed2 = await file(deeds.id, 'title-deed-2004.pdf', 'Assigned to the company, 2004');
  const deed3 = await file(deeds.id, 'title-deed-2019.pdf');
  const mort1 = await file(mortgage.id, 'mortgage-2004.pdf');
  const all = await props.documents({ propertyId: towerId });
  ck('C1 three deeds under one type all survive', all.filter((d) => d.documentTypeId === deeds.id).length === 3, JSON.stringify(all.map((d) => d.filename)));
  ck('C2 nothing was superseded', [deed1, deed2, deed3, mort1].every((a) => all.some((d) => d.id === a.id)));
  ck('C3 each still has its own file', (await Promise.all(all.map(async (d) => (await readStored((await attachments.getForDownload(staff, orgId, d.id)).storageKey)).length))).every((n) => n === DEED.length));

  console.log('\nD. Re-filing one under another type');
  await props.updateDocument({ id: deed3.id, documentTypeId: mortgage.id, caption: 'Actually the 2019 mortgage' });
  const refiled = (await props.documents({ propertyId: towerId })).find((d) => d.id === deed3.id);
  ck('D1 the type changes', refiled?.documentTypeId === mortgage.id && refiled?.typeNameEn === 'ZZ Mortgage Deed');
  ck('D2 so does the caption', refiled?.caption === 'Actually the 2019 mortgage');
  ck('D3 the stored file is untouched', (await readStored((await attachments.getForDownload(staff, orgId, deed3.id)).storageKey)).equals(DEED));
  const wrongList = await refused(() => props.updateDocument({ id: deed3.id, documentTypeId: category.id }));
  ck('D4 a value from another list is refused', wrongList.includes('Document type not found'), `got "${wrongList}"`);
  const notMine = await refused(() => props.updateDocument({ id: 'nope', documentTypeId: deeds.id }));
  ck('D5 an unknown attachment is refused', notMine.includes('Attachment not found'), `got "${notMine}"`);
  const usage = await refs.list();
  ck('D6 the option-list editor counts the files filed under each type',
    usage.find((r) => r.id === deeds.id)?.usageCount === 2 && usage.find((r) => r.id === mortgage.id)?.usageCount === 2,
    JSON.stringify(usage.filter((r) => r.domain === 'PROPERTY_DOCUMENT_TYPE').map((r) => `${r.code}=${r.usageCount}`)));

  console.log('\nE. A file has to say what it is');
  const unfiled = await refused(() => attachments.upload({ user: staff, organizationId: orgId, ownerType: 'PROPERTY', ownerId: towerId, filename: 'x.pdf', mimeType: 'application/pdf', buffer: DEED }));
  ck('E1 an unclassified upload is refused', unfiled.includes('Choose what kind of document this is'), `got "${unfiled}"`);
  const wrongDomain = await refused(() => file(category.id, 'x.pdf'));
  ck('E2 so is a type id from another list', wrongDomain.includes('Document type not found'), `got "${wrongDomain}"`);
  ck('E3 neither was stored', (await props.documents({ propertyId: towerId })).length === 4);

  console.log('\nF. A tenant reaches none of it');
  const asTenant = tenantUser(tenant.id);
  const tenantUpload = await refused(() => attachments.upload({ user: asTenant, organizationId: orgId, ownerType: 'PROPERTY', ownerId: towerId, filename: 'x.pdf', mimeType: 'application/pdf', buffer: DEED, documentTypeId: deeds.id }));
  ck('F1 a tenant cannot file one', tenantUpload.includes('Missing permission'), `got "${tenantUpload}"`);
  const tenantGhost = await refused(() => attachments.upload({ user: asTenant, organizationId: orgId, ownerType: 'PROPERTY', ownerId: 'no-such-property', filename: 'x.pdf', mimeType: 'application/pdf', buffer: DEED, documentTypeId: deeds.id }));
  ck('F2 …and is refused identically for a property that does not exist, so the refusal leaks nothing',
    tenantGhost === tenantUpload, `"${tenantGhost}" vs "${tenantUpload}"`);
  const tenantRead = await refused(() => attachments.getForDownload(asTenant, orgId, deed1.id));
  ck('F3 nor download one', tenantRead.includes('Missing permission'), `got "${tenantRead}"`);
  const tenantDelete = await refused(() => attachments.remove(asTenant, orgId, deed1.id));
  ck('F4 nor delete one', tenantDelete.includes('Missing permission'), `got "${tenantDelete}"`);
  const tenantList = await refused(() => propertiesRouter.createCaller(ctxOf(orgId, asTenant)).documents({ propertyId: towerId }));
  ck('F5 the property router refuses a tenant account outright', tenantList.includes('tenant account and cannot use the back office'), `got "${tenantList}"`);
  const portalProcedures = Object.keys((portalRouter as unknown as { _def: { procedures: Record<string, unknown> } })._def.procedures);
  ck('F6 the tenant portal has no property-document procedure at all', !portalProcedures.some((p) => /document/i.test(p)), portalProcedures.join(','));

  console.log('\nG. Permissions');
  const readOnly = staffUser(['property.read']);
  const noRead = staffUser(['property.update']);
  const cantFile = await refused(() => attachments.upload({ user: readOnly, organizationId: orgId, ownerType: 'PROPERTY', ownerId: towerId, filename: 'x.pdf', mimeType: 'application/pdf', buffer: DEED, documentTypeId: deeds.id }));
  ck('G1 filing one needs property.update', cantFile.includes('Missing permission'), `got "${cantFile}"`);
  const cantRead = await refused(() => attachments.getForDownload(noRead, orgId, deed1.id));
  ck('G2 downloading one needs property.read', cantRead.includes('Missing permission'), `got "${cantRead}"`);
  ck('G3 the list needs property.read',
    (await refused(() => propertiesRouter.createCaller(ctxOf(orgId, noRead)).documents({ propertyId: towerId }))).includes('Missing permission: property.read'));
  ck('G4 re-filing needs property.update',
    (await refused(() => propertiesRouter.createCaller(ctxOf(orgId, readOnly)).updateDocument({ id: deed1.id, documentTypeId: mortgage.id }))).includes('Missing permission: property.update'));
  ck('G5 deleting one needs property.update', (await refused(() => attachments.remove(readOnly, orgId, deed1.id))).includes('Missing permission'));

  console.log('\nH. What may be uploaded');
  const before = filesOnDisk().length;
  const badType = await refused(() => file(deeds.id, 'notes.txt', undefined, Buffer.from('hello'), 'text/plain'));
  ck('H1 a file type that is not allowed is refused', badType.includes('is not allowed'), `got "${badType}"`);
  const empty = await refused(() => file(deeds.id, 'empty.pdf', undefined, Buffer.alloc(0)));
  ck('H2 an empty file is refused', empty.includes('empty'), `got "${empty}"`);
  const huge = await refused(() => file(deeds.id, 'huge.pdf', undefined, Buffer.alloc(10 * 1024 * 1024 + 1)));
  ck('H3 a file over 10MB is refused', huge.includes('10MB'), `got "${huge}"`);
  ck('H4 none of the three left anything on disk', filesOnDisk().length === before, `${filesOnDisk().length} vs ${before}`);
  const image = await file(deeds.id, 'floor-plan.png', 'Scanned plan', PNG, 'image/png');
  ck('H5 a scan of a plan is fine', image.mimeType === 'image/png' && (await readStored(image.storageKey)).equals(PNG));

  console.log('\nI. A failed DB write takes its file with it');
  // The service writes the bytes first and the row second, so a row that never
  // lands must not leave a file nobody references. Forced here rather than
  // waited for: prisma is stubbed to fail on the one call that matters.
  const brokenPrisma = new Proxy(prisma, {
    get(target, prop, receiver) {
      if (prop === 'attachment') return { create: () => Promise.reject(new Error('ZZ simulated write failure')) };
      return Reflect.get(target, prop, receiver);
    },
  }) as unknown as PrismaService;
  const beforeFail = filesOnDisk().length;
  const failed = await refused(() =>
    new AttachmentService(brokenPrisma, storage).upload({
      user: staff, organizationId: orgId, ownerType: 'PROPERTY', ownerId: towerId,
      filename: 'doomed.pdf', mimeType: 'application/pdf', buffer: DEED, documentTypeId: deeds.id,
    }),
  );
  ck('I1 the upload fails', failed.includes('ZZ simulated write failure'), `got "${failed}"`);
  ck('I2 and nothing is orphaned in storage', filesOnDisk().length === beforeFail, `${filesOnDisk().length} vs ${beforeFail}`);

  console.log('\nJ. Another organisation sees nothing');
  const org2 = (await prisma.organization.create({ data: { code: OTHER_ORG_CODE, name: 'Property document smoke org 2' } })).id;
  const intruder = propertiesRouter.createCaller(ctxOf(org2, staff));
  ck('J1 the building is not theirs to list', (await refused(() => intruder.documents({ propertyId: towerId }))).includes('Property not found'));
  ck('J2 nor its documents theirs to download', (await refused(() => attachments.getForDownload(staff, org2, deed1.id))).includes('Attachment not found'));
  ck('J3 nor to re-file', (await refused(() => intruder.updateDocument({ id: deed1.id, documentTypeId: deeds.id }))).includes('Attachment not found'));
  ck('J4 nor to delete', (await refused(() => attachments.remove(staff, org2, deed1.id))).includes('Attachment not found'));
  const crossFile = await refused(() => attachments.upload({ user: staff, organizationId: org2, ownerType: 'PROPERTY', ownerId: towerId, filename: 'x.pdf', mimeType: 'application/pdf', buffer: DEED, documentTypeId: deeds.id }));
  ck('J5 nor to file a document on it from over there', crossFile.includes('Property not found'), `got "${crossFile}"`);
  ck('J6 and the documents are all still there', (await props.documents({ propertyId: towerId })).length === 5);

  console.log('\nK. Deleting');
  await attachments.remove(staff, orgId, image.id);
  ck('K1 a document can be removed', (await props.documents({ propertyId: towerId })).length === 4);
  ck('K2 and its file goes with it', (await refused(() => readStored(image.storageKey))).includes('ENOENT'), 'file still on disk');
  // Archiving a building is a soft delete — its deeds are the company's record
  // of what it owns, and they outlive the building being taken off the list.
  await props.archive({ id: shedId });
  await props.archive({ id: towerId });
  const afterArchive = await props.documents({ propertyId: towerId });
  ck('K3 archiving the building keeps its paperwork', afterArchive.length === 4, JSON.stringify(afterArchive.length));
  ck('K4 which is still downloadable', (await readStored((await attachments.getForDownload(staff, orgId, deed1.id)).storageKey)).equals(DEED));
  await props.restore({ id: towerId });
  ck('K5 and restoring changes nothing about it', (await props.documents({ propertyId: towerId })).length === 4);
}

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);
  });
