/**
 * Functional smoke for the landlord companies and the fields that hang off them.
 *
 * The group owns its buildings through ~20 separate limited companies, and the
 * system had no idea they existed: the single Organization row was the only
 * company identity. This covers the new master data and the three things that
 * now point at reference values — the property's category, and the lease's type
 * and use.
 *
 * The behaviours that matter and are easy to lose:
 *   · a reference value is only valid for its OWN list — the ids are one space,
 *     so a property category passed as a lease type must be refused, not stored
 *     and read back blank;
 *   · a landlord that still owns a building cannot be archived, or the property
 *     is left pointing at an owner nobody can see;
 *   · the lease never stores the landlord or the category. They are the
 *     property's, derived on read, so the two can never disagree.
 *
 * Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/landlord-property-smoke.ts
 */
import 'reflect-metadata';
import { PrismaService } from '../src/prisma/prisma.service';
import { landlordsRouter } from '../src/trpc/routers/landlords.router';
import { leasesRouter } from '../src/trpc/routers/leases.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';
import { importLandlords } from './import-landlords';

const prisma = new PrismaService();

let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };

// Landlord codes are two letters now, too short to mark as ours by prefix, so
// the companies this smoke makes are recognised by name instead.
const NAME = 'ZZ ';
/** Account codes no chart of the office's uses (9999 is its suspense range). */
const ZZ_ACCOUNTS = '9999-90-00';
const REF_CODES = ['ZZ_CAT', 'ZZ_CAT2', 'ZZ_LTYPE', 'ZZ_USE', 'ZZ_REGION'];
const PROP = 'ZZ Landlord Property';
const PROP2 = 'ZZ Landlord Property 2';
const OTHER_PROP = 'ZZ Other Org Property';
const TENANT = 'ZZ Landlord Tenant';
const LEASE_REF = 'ZZ-LL-1';
const OTHER_ORG = 'ZZ-ORG2';

const PERMS = [
  'landlord.read', 'landlord.create', 'landlord.update', 'landlord.delete',
  'property.read', 'property.create', 'property.update', 'property.delete',
  'lease.read', 'lease.create', 'lease.update',
  'reference-value.read', 'reference-value.create', 'reference-value.update',
];

function staffCtx(orgId: string): Context {
  const user: AuthUser = { id: 'zz-ll-staff', email: 'zz@rms.local', name: 'ZZ', tenantId: null, mustChangePassword: false, roles: ['ADMIN'], permissions: PERMS };
  return { prisma, user, organizationId: orgId } as unknown as Context;
}

async function refused(fn: () => Promise<unknown>): Promise<string> {
  try {
    await fn();
    return '';
  } catch (e) {
    return e instanceof Error ? e.message : String(e);
  }
}

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;

  await purgeStale();

  const landlords = landlordsRouter.createCaller(staffCtx(orgId));
  const properties = propertiesRouter.createCaller(staffCtx(orgId));
  const leases = leasesRouter.createCaller(staffCtx(orgId));
  const refValues = referenceValuesRouter.createCaller(staffCtx(orgId));

  // A second organisation, so "org-scoped" can be tested rather than assumed.
  const other = await prisma.organization.create({ data: { code: OTHER_ORG, name: 'ZZ Other Org' } });
  const otherLandlords = landlordsRouter.createCaller(staffCtx(other.id));
  const otherProperties = propertiesRouter.createCaller(staffCtx(other.id));

  console.log('A. A landlord company can be created, read back and edited');
  // Codes of a range the office's chart does not use, in the real organisation:
  // purged with the landlords that name them.
  const zzAccount = (code: string) => prisma.glAccount.create({ data: { organizationId: orgId, code, name: `ZZ ${code}`, type: 'ASSET' } });
  const [zaAcct, zaAcct2] = [await zzAccount(`${ZZ_ACCOUNTS}01`), await zzAccount(`${ZZ_ACCOUNTS}02`)];
  const created = await landlords.create({
    code: 'za', name: 'ZZ All Link International Limited', nameZh: 'ZZ 全連',
    glAccountId: zaAcct.id, address: 'ZZ Central', tel: '21234567', email: 'zz@landlord.test',
    isActive: true, sortOrder: 10,
  });
  const got = await landlords.get({ id: created.id });
  ck('A1 the code is stored upper-case', got.code === 'ZA', `got ${got.code}`);
  ck('A2 its account is kept', got.glAccountId === zaAcct.id && got.account?.code === zaAcct.code, `got ${JSON.stringify(got.account)}`);
  ck('A3 the letterhead details are kept', got.address === 'ZZ Central' && got.tel === '21234567' && got.email === 'zz@landlord.test');
  ck('A4 it owns nothing yet', got.properties === 0, `got ${got.properties}`);
  await landlords.update({ id: created.id, code: 'ZA', name: 'ZZ All Link Int’l Limited', nameZh: 'ZZ 全連', glAccountId: zaAcct2.id, address: null, tel: null, email: null, isActive: true, sortOrder: 10 });
  const edited = await landlords.get({ id: created.id });
  ck('A5 a rename lands', edited.name === 'ZZ All Link Int’l Limited', `got ${edited.name}`);
  ck('A6 and clearing a field clears it', edited.address === null && edited.tel === null);
  await landlords.setActive({ id: created.id, isActive: false });
  const afterOff = (await landlords.list()).find((l) => l.id === created.id);
  ck('A7 deactivating keeps it on the management list', afterOff?.isActive === false, `got ${JSON.stringify(afterOff?.isActive)}`);
  await landlords.setActive({ id: created.id, isActive: true });

  console.log('');
  console.log('B. A duplicate code is refused');
  const dup = await refused(() => landlords.create({ code: 'ZA', name: 'ZZ Copycat Limited', isActive: true, sortOrder: 0 }));
  ck('B1 refused with a sentence', dup.includes('already exists'), `got "${dup}"`);
  const second = await landlords.create({ code: 'ZB', name: 'ZZ Blossom Properties Limited', isActive: true, sortOrder: 20 });
  const dupEdit = await refused(() => landlords.update({ id: second.id, code: 'ZA', name: 'ZZ Blossom Properties Limited', isActive: true, sortOrder: 20 }));
  ck('B2 and renaming one onto another’s code is refused too', dupEdit.includes('already exists'), `got "${dupEdit}"`);

  console.log('');
  console.log('C. Everything is scoped to the caller’s organisation');
  const foreign = await otherLandlords.create({ code: 'ZF', name: 'ZZ Foreign Holdings Limited', isActive: true, sortOrder: 0 });
  const foreignGet = await refused(() => landlords.get({ id: foreign.id }));
  ck('C1 another org’s landlord cannot be read', foreignGet.includes('not found'), `got "${foreignGet}"`);
  const foreignEdit = await refused(() => landlords.update({ id: foreign.id, code: 'ZF', name: 'ZZ Hijacked', isActive: true, sortOrder: 0 }));
  ck('C2 nor edited', foreignEdit.includes('not found'), `got "${foreignEdit}"`);
  ck('C3 nor listed', !(await landlords.list()).some((l) => l.id === foreign.id));
  ck('C4 and ours is invisible the other way', !(await otherLandlords.list()).some((l) => l.id === created.id));
  const foreignCategory = await prisma.referenceValue.create({
    data: { organizationId: other.id, domain: 'PROPERTY_CATEGORY', code: 'ZZ_CAT2', nameEn: 'ZZ Foreign Category', sortOrder: 900 },
  });

  console.log('');
  console.log('D. A property records who owns it and what it is');
  const category = await refValues.create({ domain: 'PROPERTY_CATEGORY', code: 'ZZ_CAT', nameEn: 'ZZ Special', nameZh: 'ZZ 特殊', sortOrder: 900, isActive: true });
  const leaseType = await refValues.create({ domain: 'LEASE_TYPE', code: 'ZZ_LTYPE', nameEn: 'ZZ Fixed', nameZh: 'ZZ 定期', sortOrder: 900, isActive: true });
  const usage = await refValues.create({ domain: 'LEASE_USAGE', code: 'ZZ_USE', nameEn: 'ZZ Godown', nameZh: 'ZZ 貨倉', sortOrder: 900, isActive: true });

  const property = await properties.create({ name: PROP, address: 'ZZ Road 1', landlordId: created.id, categoryId: category.id, units: [{ name: 'ZZ LL A' }] });
  const propGot = await properties.get({ id: property.id });
  ck('D1 the owning company is read back', propGot.landlordId === created.id && propGot.landlordCode === 'ZA', `got ${propGot.landlordCode}`);
  ck('D2 with its name, for display', propGot.landlordName === 'ZZ All Link Int’l Limited', `got ${propGot.landlordName}`);
  ck('D3 and the category', propGot.categoryId === category.id);
  const row = (await properties.list()).find((p) => p.id === property.id);
  ck('D4 the list carries the owner without a second call', row?.landlordCode === 'ZA' && row?.landlordName === 'ZZ All Link Int’l Limited');
  // Both names travel: the same screen renders these beside a picker that
  // follows the UI language, so the server must not pick one for it.
  ck('D5 and the category’s name in both languages', row?.categoryNameEn === 'ZZ Special' && row?.categoryNameZh === 'ZZ 特殊', `got ${row?.categoryNameEn} / ${row?.categoryNameZh}`);
  ck('D5b as does the owner’s', row?.landlordNameZh === 'ZZ 全連', `got ${row?.landlordNameZh}`);

  const wrongList = await refused(() => properties.create({ name: PROP2, landlordId: created.id, categoryId: usage.id }));
  ck('D6 a value from another list is not a category', wrongList.includes('Property category not found'), `got "${wrongList}"`);
  const foreignLandlord = await refused(() => properties.create({ name: PROP2, landlordId: foreign.id }));
  ck('D7 nor can another org’s company own it', foreignLandlord.includes('Landlord not found'), `got "${foreignLandlord}"`);
  const foreignCat = await refused(() => properties.create({ name: PROP2, categoryId: foreignCategory.id }));
  ck('D8 nor another org’s category', foreignCat.includes('Property category not found'), `got "${foreignCat}"`);

  const form = await properties.formData();
  ck('D9 the property form offers this org’s companies', form.landlords.some((l) => l.id === created.id) && !form.landlords.some((l) => l.id === foreign.id));
  ck('D10 and its categories', form.categories.some((c) => c.id === category.id));

  console.log('');
  console.log('E. A company that still owns a building cannot be archived');
  const blocked = await refused(() => landlords.archive({ id: created.id }));
  ck('E1 refused, and it says how many', blocked.includes('still owns 1 property'), `got "${blocked}"`);
  ck('E2 and the list says so too', (await landlords.list()).find((l) => l.id === created.id)?.properties === 1);
  await properties.update({ id: property.id, name: PROP, landlordId: second.id, categoryId: category.id });
  const moved = await properties.get({ id: property.id });
  ck('E3 reassigning moves it', moved.landlordId === second.id, `got ${moved.landlordId}`);
  await landlords.archive({ id: created.id });
  ck('E4 now it can be archived', !(await landlords.list()).some((l) => l.id === created.id));
  ck('E5 and is still there when archived ones are asked for', (await landlords.list({ includeArchived: true })).some((l) => l.id === created.id && l.archived));
  await landlords.restore({ id: created.id });
  ck('E6 restoring brings it back', (await landlords.list()).some((l) => l.id === created.id));

  // Archiving a building is not letting go of it. If it did not count, the
  // owner could be archived behind it, and restoring the building would leave a
  // live property naming a company the pickers no longer offer.
  await properties.archive({ id: property.id });
  const stillOwned = await refused(() => landlords.archive({ id: second.id }));
  ck('E7 an archived building still counts as owned', stillOwned.includes('still owns 1 property'), `got "${stillOwned}"`);
  ck('E8 and the number on the list is the number the guard used', (await landlords.list()).find((l) => l.id === second.id)?.properties === 1);
  await properties.restore({ id: property.id });

  // That guard and the check on save are not one transaction, so a company can
  // still be archived in the gap between them. The property that already names
  // it stays saveable — same stance a deactivated one gets.
  await prisma.landlord.update({ where: { id: second.id }, data: { deletedAt: new Date() } });
  await properties.update({ id: property.id, name: PROP, landlordId: second.id, categoryId: category.id });
  ck('E9 an owner already named stays saveable once archived', (await properties.get({ id: property.id })).landlordId === second.id);
  const newlyArchived = await refused(() => properties.create({ name: PROP2, landlordId: second.id }));
  ck('E10 but it can never be newly assigned', newlyArchived.includes('Landlord not found'), `got "${newlyArchived}"`);
  await prisma.landlord.update({ where: { id: second.id }, data: { deletedAt: null } });

  console.log('');
  console.log('F. A lease records its type, its use and its notice period');
  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: TENANT } });
  const unit = await prisma.unit.findFirstOrThrow({ where: { propertyId: property.id }, select: { id: true } });
  const lease = await leases.create({
    reference: LEASE_REF, tenantId: tenant.id, status: 'DRAFT', currency: 'HKD',
    startDate: '2030-01-01', endDate: '2032-12-31', depositMonths: 0,
    leaseTypeId: leaseType.id, usageId: usage.id, noticeDays: 60, unitIds: [unit.id],
  });
  const leaseGot = await leases.get({ id: lease.id });
  ck('F1 the lease type is read back, with the name the form shows', leaseGot.leaseTypeId === leaseType.id && leaseGot.leaseType?.code === 'ZZ_LTYPE', `got ${JSON.stringify(leaseGot.leaseType)}`);
  ck('F2 the use as well', leaseGot.usageId === usage.id);
  ck('F3 and the notice period', leaseGot.noticeDays === 60, `got ${leaseGot.noticeDays}`);

  const crossed = await refused(() => leases.update({
    id: lease.id, reference: LEASE_REF, tenantId: tenant.id, status: 'DRAFT', currency: 'HKD',
    startDate: '2030-01-01', endDate: '2032-12-31', depositMonths: 0, leaseTypeId: usage.id, unitIds: [unit.id],
  }));
  ck('F4 a use is not a lease type', crossed.includes('Lease type not found'), `got "${crossed}"`);
  const crossed2 = await refused(() => leases.update({
    id: lease.id, reference: LEASE_REF, tenantId: tenant.id, status: 'DRAFT', currency: 'HKD',
    startDate: '2030-01-01', endDate: '2032-12-31', depositMonths: 0, usageId: category.id, unitIds: [unit.id],
  }));
  ck('F5 and a property category is not a use', crossed2.includes('Lease usage not found'), `got "${crossed2}"`);

  await leases.update({
    id: lease.id, reference: LEASE_REF, tenantId: tenant.id, status: 'DRAFT', currency: 'HKD',
    startDate: '2030-01-01', endDate: '2032-12-31', depositMonths: 0, unitIds: [unit.id],
  });
  const cleared = await leases.get({ id: lease.id });
  ck('F6 all three can be cleared', cleared.leaseTypeId === null && cleared.usageId === null && cleared.noticeDays === null);

  const leaseForm = await leases.formData();
  ck('F7 the lease form is offered the types', leaseForm.leaseTypes.some((v) => v.id === leaseType.id));
  ck('F8 and the uses', leaseForm.usages.some((v) => v.id === usage.id));
  // Retiring a value takes it out of the pickers; it does not rewrite the
  // leases that already name it, so the form has to be able to name it too —
  // otherwise the select reads "not stated" while the id is quietly still
  // there, and the next save writes it straight back.
  await leases.update({
    id: lease.id, reference: LEASE_REF, tenantId: tenant.id, status: 'DRAFT', currency: 'HKD',
    startDate: '2030-01-01', endDate: '2032-12-31', depositMonths: 0, usageId: usage.id, unitIds: [unit.id],
  });
  await refValues.setActive({ id: usage.id, isActive: false });
  ck('F9 a retired use is no longer offered', !(await leases.formData()).usages.some((v) => v.id === usage.id));
  const retired = await leases.get({ id: lease.id });
  ck('F10 but the lease that already names it still reads its name back', retired.usageId === usage.id && retired.usage?.nameZh === 'ZZ 貨倉', `got ${JSON.stringify(retired.usage)}`);
  await refValues.setActive({ id: usage.id, isActive: true });

  console.log('');
  console.log('G. The lease form shows the property’s owner and category — the lease never stores them');
  const unitOffered = async () => (await leases.formData()).buildings.flatMap((b) => b.units).find((u) => u.id === unit.id);
  const derived = await unitOffered();
  ck('G1 the owning company comes through', derived?.landlordCode === 'ZB' && derived?.landlordName === 'ZZ Blossom Properties Limited', `got ${JSON.stringify(derived)}`);
  ck('G2 and the category by name', derived?.categoryNameZh === 'ZZ 特殊', `got ${derived?.categoryNameZh}`);
  await properties.update({ id: property.id, name: PROP, landlordId: created.id, categoryId: category.id });
  const after = await unitOffered();
  ck('G3 changing it on the property changes it on the lease', after?.landlordCode === 'ZA', `got ${after?.landlordCode}`);

  console.log('');
  console.log('H. The three newly-opened lists are editable; the closed ones are not');
  const listed = await refValues.list();
  ck('H1 property categories are on the editor', listed.some((v) => v.id === category.id && v.domain === 'PROPERTY_CATEGORY'));
  ck('H2 lease types too', listed.some((v) => v.id === leaseType.id && v.domain === 'LEASE_TYPE'));
  ck('H3 and lease uses', listed.some((v) => v.id === usage.id && v.domain === 'LEASE_USAGE'));
  ck('H4 usage is counted, so retiring one is an informed choice', (listed.find((v) => v.id === category.id)?.usageCount ?? 0) === 1, `got ${listed.find((v) => v.id === category.id)?.usageCount}`);
  const region = await prisma.referenceValue.create({
    data: { organizationId: orgId, domain: 'REGION', code: 'ZZ_REGION', nameEn: 'ZZ Region', sortOrder: 900 },
  });
  ck('H5 a list that stays closed is not shown', !(await refValues.list()).some((v) => v.id === region.id));
  const closedEdit = await refused(() => refValues.update({ id: region.id, nameEn: 'ZZ Hijacked Region', sortOrder: 0, isActive: true }));
  ck('H6 nor editable', closedEdit.includes('not found'), `got "${closedEdit}"`);
  const closedCreate = await refused(() => refValues.create({ domain: 'REGION' as never, code: 'ZZ_REGION2', nameEn: 'ZZ Region 2', sortOrder: 0, isActive: true }));
  ck('H7 nor can one be added to it', closedCreate !== '', `got "${closedCreate}"`);
  const foreignValue = await refused(() => refValues.update({ id: foreignCategory.id, nameEn: 'ZZ Hijacked', sortOrder: 0, isActive: true }));
  ck('H8 and another org’s value is out of reach', foreignValue.includes('not found'), `got "${foreignValue}"`);

  console.log('');
  console.log('I. The landlord import can be run again without duplicating anything');
  const rows = [
    { code: 'ZI', name: 'ZZ Import One Limited', accountCode: `${ZZ_ACCOUNTS}11` },
    { code: 'ZJ', name: 'ZZ Import Two Limited', accountCode: `${ZZ_ACCOUNTS}12` },
  ];
  const first = await importLandlords(prisma, orgId, rows);
  ck('I1 the first run creates every row', first.created.length === 2 && first.updated.length === 0, JSON.stringify(first));
  const zi = await prisma.landlord.findFirstOrThrow({ where: { organizationId: orgId, code: 'ZI' }, select: { glAccount: { select: { code: true, name: true } } } });
  ck('I1b each names its account, added to the chart when missing', zi.glAccount?.code === rows[0].accountCode && zi.glAccount.name === rows[0].name, JSON.stringify(zi));
  const again = await importLandlords(prisma, orgId, rows);
  ck('I2 a second run changes nothing', again.created.length === 0 && again.updated.length === 0 && again.unchanged.length === 2, JSON.stringify(again));
  ck('I3 and there is still one row per company', (await prisma.landlord.count({ where: { organizationId: orgId, code: { in: ['ZI', 'ZJ'] } } })) === 2);
  const renamed = await importLandlords(prisma, orgId, [{ ...rows[0], name: 'ZZ Import One (HK) Limited' }, rows[1]]);
  ck('I4 a corrected name is applied', renamed.updated.length === 1 && renamed.unchanged.length === 1, JSON.stringify(renamed));
  // What the office typed in the admin is theirs; the spreadsheet only owns the
  // name and the accounting code.
  await prisma.landlord.updateMany({ where: { organizationId: orgId, code: 'ZJ' }, data: { nameZh: 'ZZ 二號', isActive: false } });
  await importLandlords(prisma, orgId, rows);
  const kept = await prisma.landlord.findFirstOrThrow({ where: { organizationId: orgId, code: 'ZJ' }, select: { nameZh: true, isActive: true } });
  ck('I5 an import does not undo what the office edited', kept.nameZh === 'ZZ 二號' && kept.isActive === false);

  console.log('');
  console.log('J. Another organisation cannot reach our property either');
  const foreignProp = await refused(() => otherProperties.get({ id: property.id }));
  ck('J1 refused', foreignProp !== '', `got "${foreignProp}"`);
  await otherProperties.create({ name: OTHER_PROP, landlordId: foreign.id });
  ck('J2 and its own property is invisible to us', !(await properties.list()).some((p) => p.name === OTHER_PROP));
}

async function purgeStale() {
  const leaseRows = await prisma.lease.findMany({ where: { reference: { startsWith: 'ZZ-LL' } }, select: { id: true } });
  for (const l of leaseRows) {
    await prisma.leaseUnit.deleteMany({ where: { leaseId: l.id } });
    await prisma.chargeRule.deleteMany({ where: { leaseId: l.id } });
    await prisma.leaseLabelOnLease.deleteMany({ where: { leaseId: l.id } });
    await prisma.lease.delete({ where: { id: l.id } }).catch(() => {});
  }
  const props = await prisma.property.findMany({ where: { name: { in: [PROP, PROP2, OTHER_PROP] } }, 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: TENANT } });
  await prisma.landlord.deleteMany({ where: { name: { startsWith: NAME } } });
  await prisma.glAccount.deleteMany({ where: { code: { startsWith: ZZ_ACCOUNTS } } });
  await prisma.referenceValue.deleteMany({ where: { code: { in: [...REF_CODES, 'ZZ_REGION2'] } } });
  await prisma.organization.deleteMany({ where: { code: OTHER_ORG } });
}

async function cleanup() {
  try { 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); });
