/**
 * Optional demo fixture — deliberately NOT part of the seed, so a real
 * deployment still starts with configuration only and no invented portfolio.
 *
 * Creates one complete, walkable scenario: a login for each department, a
 * property with two units, an active lease with charge rules, and a held
 * deposit. That is everything needed to exercise the full loop —
 *
 *   generate draft → send for approval → Leasing approves → Accounting
 *   approves → issue → terminate the lease → settle the deposit
 *
 * Run: cd apps/api && npm run demo:fixture     (create, replacing any previous)
 *      cd apps/api && npm run demo:clear       (remove everything it made)
 */
import 'reflect-metadata';
import { randomBytes, scryptSync } from 'node:crypto';
import { ApprovalService } from '../src/approvals/approval.service';
import { DepositsService } from '../src/deposits/deposits.service';
import { LedgerService } from '../src/ledger/ledger.service';
import { NumberService } from '../src/common/number.service';
import { PrismaService } from '../src/prisma/prisma.service';

const prisma = new PrismaService();
const deposits = new DepositsService(prisma, new LedgerService(), new NumberService(), new ApprovalService(prisma));

const LEASE_REF = 'DEMO-L1';
const PROPERTY = 'Demo Court';
const LOGINS = [
  { email: 'leasing@rms.local', name: 'Leasing Officer', role: 'LEASING' },
  { email: 'accounting@rms.local', name: 'Accounting Officer', role: 'ACCOUNTING' },
];

/** Same scrypt$salt$hash format the seed and the auth module use. */
function hashPassword(plain: string): string {
  const salt = randomBytes(16).toString('hex');
  return `scrypt$${salt}$${scryptSync(plain, salt, 64).toString('hex')}`;
}

async function clear(): Promise<void> {
  const lease = await prisma.lease.findUnique({ where: { reference: LEASE_REF }, select: { id: true } });
  if (lease) {
    const invoices = await prisma.invoice.findMany({ where: { leaseId: lease.id }, select: { id: true } });
    const depositRows = await prisma.deposit.findMany({ where: { leaseId: lease.id }, select: { id: true } });
    const invIds = invoices.map((i) => i.id);
    const depIds = depositRows.map((d) => d.id);
    const docIds = [...invIds, ...depIds, lease.id];

    await prisma.approvalAction.deleteMany({ where: { instance: { documentId: { in: [...invIds, ...depIds] } } } });
    await prisma.approvalInstance.deleteMany({ where: { documentId: { in: [...invIds, ...depIds] } } });
    await prisma.journalLine.deleteMany({ where: { OR: [{ invoiceId: { in: invIds } }, { leaseId: lease.id }, { entry: { sourceId: { in: docIds } } }] } });
    await prisma.journalEntry.deleteMany({ where: { sourceId: { in: docIds } } });
    await prisma.depositSettlementLine.deleteMany({ where: { settlement: { depositId: { in: depIds } } } });
    await prisma.depositSettlement.deleteMany({ where: { depositId: { in: depIds } } });
    await prisma.depositAllocation.deleteMany({ where: { depositId: { in: depIds } } });
    await prisma.deposit.deleteMany({ where: { id: { in: depIds } } });
    await prisma.receiptAllocationItem.deleteMany({ where: { invoiceId: { in: invIds } } });
    await prisma.invoiceLine.deleteMany({ where: { invoiceId: { in: invIds } } });
    await prisma.invoice.deleteMany({ where: { id: { in: invIds } } });
    await prisma.chargeRule.deleteMany({ where: { leaseId: lease.id } });
    await prisma.leaseUnit.deleteMany({ where: { leaseId: lease.id } });
    await prisma.lease.delete({ where: { id: lease.id } });
  }

  const props = await prisma.property.findMany({ where: { name: PROPERTY }, select: { id: true } });
  if (props.length) {
    const ids = props.map((p) => p.id);
    await prisma.unit.deleteMany({ where: { propertyId: { in: ids } } });
    await prisma.property.deleteMany({ where: { id: { in: ids } } });
  }

  const users = await prisma.user.findMany({ where: { email: { in: LOGINS.map((l) => l.email) } }, select: { id: true } });
  if (users.length) {
    const ids = users.map((u) => u.id);
    await prisma.userRole.deleteMany({ where: { userId: { in: ids } } });
    await prisma.user.deleteMany({ where: { id: { in: ids } } });
  }
}

async function create(): Promise<void> {
  const org = await prisma.organization.findUnique({ where: { code: 'MAIN' }, select: { id: true } });
  if (!org) throw new Error('No MAIN organization — run `npm run prisma:seed` first.');
  const orgId = org.id;

  const password = process.env.DEMO_PASSWORD ?? 'demo1234';
  for (const l of LOGINS) {
    const role = await prisma.role.findUnique({ where: { code: l.role }, select: { id: true } });
    if (!role) throw new Error(`Role ${l.role} is missing — run \`npm run prisma:seed\` first.`);
    await prisma.user.create({
      data: { email: l.email, name: l.name, passwordHash: hashPassword(password), locale: 'zh-HK', roles: { create: { roleId: role.id } } },
    });
  }

  // The portal login hangs off the seeded tenant, so attaching the demo lease to
  // it means tenant@rms.local can see the resulting debit notes too.
  const tenant = await prisma.tenant.findFirst({ where: { organizationId: orgId }, orderBy: { createdAt: 'asc' } });
  if (!tenant) throw new Error('No tenant — run `npm run prisma:seed` first.');

  const chargeType = async (code: string) => {
    const c = await prisma.chargeType.findUnique({ where: { organizationId_code: { organizationId: orgId, code } }, select: { id: true } });
    if (!c) throw new Error(`Charge type ${code} is missing — run \`npm run prisma:seed\` first.`);
    return c.id;
  };
  const rent = await chargeType('RENT');
  const mgmt = await chargeType('MGMT_FEE');

  const property = await prisma.property.create({
    data: {
      organizationId: orgId,
      name: PROPERTY,
      address: '1 Demo Road, Central',
      units: {
        create: [
          { name: 'Flat A', area: '650.00', status: 'OCCUPIED' },
          { name: 'Flat B', area: '720.00', status: 'AVAILABLE' },
        ],
      },
    },
  });
  const flatA = await prisma.unit.findFirstOrThrow({ where: { propertyId: property.id, name: 'Flat A' } });

  const lease = await prisma.lease.create({
    data: {
      organizationId: orgId,
      reference: LEASE_REF,
      tenantId: tenant.id,
      status: 'ACTIVE',
      currency: 'HKD',
      // A long term with a mid-point start, so any current period bills in full
      // and there is plenty of room to pick an early termination date.
      startDate: new Date('2026-01-01'),
      endDate: new Date('2027-12-31'),
      depositMonths: 2,
      dueDayOfMonth: 10,
      units: { create: { unitId: flatA.id } },
      chargeRules: {
        create: [
          { chargeTypeId: rent, amount: '31000.00', frequencyMonths: 1, timing: 'ADVANCE', proration: 'DAILY', sortOrder: 0 },
          { chargeTypeId: mgmt, amount: '1200.00', frequencyMonths: 1, timing: 'ADVANCE', proration: 'DAILY', sortOrder: 1 },
        ],
      },
    },
  });

  const deposit = await deposits.create({ organizationId: orgId, tenantId: tenant.id, leaseId: lease.id, amount: '62000' });

  console.log('Demo fixture ready:');
  console.log(`  property   ${PROPERTY} (Flat A occupied, Flat B available)`);
  console.log(`  lease      ${LEASE_REF} · ${tenant.name} · rent 31,000 + mgmt 1,200 / month · 2026-01-01 → 2027-12-31`);
  console.log(`  deposit    ${deposit.number} · HK$62,000 held`);
  console.log('  logins     leasing@rms.local (租賃部) · accounting@rms.local (會計部)');
  console.log(`             password: ${process.env.DEMO_PASSWORD ? '<DEMO_PASSWORD>' : 'demo1234'}`);
  console.log('\nWalk it: Debit Notes → Generate Draft → Send for approval →');
  console.log('  sign in as leasing → My Approvals → Approve →');
  console.log('  sign in as accounting → Approve → Issue →');
  console.log('  Leases → Terminate → Deposits → Settle.');
}

const mode = process.argv.includes('--clear') ? 'clear' : 'create';

(async () => {
  await clear();
  if (mode === 'create') await create();
  else console.log('Demo fixture removed.');
})()
  .catch((e) => {
    console.error(e instanceof Error ? e.message : e);
    process.exitCode = 1;
  })
  .finally(() => prisma.$disconnect());
