/**
 * Functional smoke for the maintenance taxonomy.
 *
 * The seed comment has always claimed these are "user-configurable, not
 * hardcoded (replaces the legacy's numeric-string priority/category baked into
 * PHP controllers)". Nothing could write one but seed.ts, so they were exactly
 * as hardcoded, only in TypeScript.
 *
 * The behaviour that has to hold once they ARE editable: retiring a value must
 * not rewrite history. A request filed under it keeps reading correctly, in the
 * back office and in the tenant's app, while the value stops being offered.
 * That asymmetry is the whole feature and C asserts both halves.
 *
 * Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/reference-value-smoke.ts
 */
import 'reflect-metadata';
import { PrismaService } from '../src/prisma/prisma.service';
import { maintenanceRouter } from '../src/trpc/routers/maintenance.router';
import { portalRouter } from '../src/trpc/routers/portal.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();

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

const CODES = ['ZZ_LIFT', 'ZZ_ROOF', 'ZZ_WHENEVER'];
const PROP = 'ZZ Ref Property';
const TENANT = 'ZZ Ref Tenant';

const PERMS = ['reference-value.read', 'reference-value.create', 'reference-value.update', 'maintenance.read', 'maintenance.create'];

function staffCtx(orgId: string): Context {
  const user: AuthUser = { id: 'zz-ref-staff', email: 'zz@rms.local', name: 'ZZ', tenantId: null, mustChangePassword: false, roles: ['ADMIN'], permissions: PERMS };
  return { prisma, user, organizationId: orgId } as unknown as Context;
}
function tenantCtx(orgId: string, tenantId: string): Context {
  const user: AuthUser = { id: 'zz-ref-tenant', email: 'zzt@rms.local', name: 'ZZ', tenantId, mustChangePassword: false, roles: ['TENANT'], permissions: [] };
  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 admin = referenceValuesRouter.createCaller(staffCtx(orgId));
  const maintenance = maintenanceRouter.createCaller(staffCtx(orgId));

  const tenant = await prisma.tenant.create({ data: { organizationId: orgId, name: TENANT } });
  const property = await prisma.property.create({
    data: { organizationId: orgId, name: PROP, units: { create: [{ name: 'ZZ Ref A' }] } },
    include: { units: true },
  });
  const portal = portalRouter.createCaller(tenantCtx(orgId, tenant.id));

  console.log('A. The lists can be added to');
  const cat = await admin.create({ domain: 'MAINTENANCE_CATEGORY', code: 'ZZ_LIFT', nameEn: 'ZZ Lift', nameZh: '升降機', sortOrder: 900, isActive: true });
  const pri = await admin.create({ domain: 'MAINTENANCE_PRIORITY', code: 'ZZ_WHENEVER', nameEn: 'ZZ Whenever', nameZh: '有空先', sortOrder: 900, isActive: true });
  const listed = await admin.list();
  ck('A1 a new category appears', listed.some((r) => r.id === cat.id && r.domain === 'MAINTENANCE_CATEGORY'));
  ck('A2 a new priority appears', listed.some((r) => r.id === pri.id && r.domain === 'MAINTENANCE_PRIORITY'));
  ck('A3 the code is stored upper-case', (await admin.list()).find((r) => r.id === cat.id)?.code === 'ZZ_LIFT');

  const form = await maintenance.formData();
  ck('A4 and both are offered when raising a request', form.categories.some((c) => c.id === cat.id) && form.priorities.some((p) => p.id === pri.id));
  const tenantOptions = await portal.reportOptions();
  ck('A5 the new priority reaches the tenant’s app too', tenantOptions.priorities.some((p) => p.id === pri.id));

  console.log('');
  console.log('B. A duplicate code in the same list is refused');
  const dup = await refused(() => admin.create({ domain: 'MAINTENANCE_CATEGORY', code: 'ZZ_LIFT', nameEn: 'ZZ Dup', sortOrder: 901, isActive: true }));
  ck('B1 refused with a sentence', dup.includes('already exists'), `got "${dup}"`);
  // The unique index is per domain, so the same code in the other list is fine.
  const other = await admin.create({ domain: 'MAINTENANCE_PRIORITY', code: 'ZZ_LIFT', nameEn: 'ZZ Lift priority', sortOrder: 902, isActive: true });
  ck('B2 but the same code in the other list is allowed', Boolean(other.id));
  await admin.setActive({ id: other.id, isActive: false });

  console.log('');
  console.log('C. Retiring one does not rewrite the requests already filed under it');
  const req = await prisma.maintenanceRequest.create({
    data: {
      organizationId: orgId, propertyId: property.id, unitId: property.units[0].id, tenantId: tenant.id,
      title: 'ZZ Lift stuck', description: 'ZZ', status: 'OPEN', categoryId: cat.id, priorityId: pri.id,
    },
  });
  const usedCat = (await admin.list()).find((r) => r.id === cat.id);
  ck('C1 usage is reported, so retiring one is an informed choice', (usedCat?.usageCount ?? 0) >= 1, `got ${usedCat?.usageCount}`);

  await admin.setActive({ id: cat.id, isActive: false });
  await admin.setActive({ id: pri.id, isActive: false });

  const rows = await maintenance.list();
  const row = rows.find((r) => r.id === req.id);
  ck('C2 the request still shows its category by name', row?.category === 'ZZ Lift', `got ${row?.category}`);
  ck('C3 and its priority', row?.priority === 'ZZ Whenever', `got ${row?.priority}`);

  const afterForm = await maintenance.formData();
  ck('C4 but neither is offered for a new request', !afterForm.categories.some((c) => c.id === cat.id) && !afterForm.priorities.some((p) => p.id === pri.id));
  const afterTenant = await portal.reportOptions();
  ck('C5 nor to the tenant', !afterTenant.priorities.some((p) => p.id === pri.id));
  ck('C6 and it is still on the management screen, so it can come back', (await admin.list()).some((r) => r.id === cat.id));

  console.log('');
  console.log('D. Renaming lands everywhere, including on old requests');
  await admin.setActive({ id: cat.id, isActive: true });
  await admin.update({ id: cat.id, nameEn: 'ZZ Lift & escalator', nameZh: '升降機及電梯', sortOrder: 900, isActive: true });
  const renamed = (await maintenance.list()).find((r) => r.id === req.id);
  ck('D1 the old request shows the new name', renamed?.category === 'ZZ Lift & escalator', `got ${renamed?.category}`);
  ck('D2 the code is untouched — records refer to it', (await admin.list()).find((r) => r.id === cat.id)?.code === 'ZZ_LIFT');
}

async function purgeStale() {
  await prisma.maintenanceTask.deleteMany({ where: { request: { title: 'ZZ Lift stuck' } } }).catch(() => {});
  await prisma.maintenanceRequest.deleteMany({ where: { title: 'ZZ Lift stuck' } });
  const props = await prisma.property.findMany({ where: { name: 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.referenceValue.deleteMany({ where: { code: { in: CODES } } });
}

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