import { randomBytes, scryptSync } from 'node:crypto';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

/**
 * Dev password hashing (scrypt, dependency-free). The auth module will reuse
 * this same `scrypt$salt$hash` format when it is built.
 */
function hashPassword(plain: string): string {
  const salt = randomBytes(16).toString('hex');
  const hash = scryptSync(plain, salt, 64).toString('hex');
  return `scrypt$${salt}$${hash}`;
}

async function main() {
  const adminPassword = process.env.SEED_ADMIN_PASSWORD ?? 'admin123';
  const tenantPassword = process.env.SEED_TENANT_PASSWORD ?? 'tenant123';
  if (process.env.NODE_ENV === 'production' && (!process.env.SEED_ADMIN_PASSWORD || !process.env.SEED_TENANT_PASSWORD)) {
    throw new Error('SEED_ADMIN_PASSWORD and SEED_TENANT_PASSWORD are required when seeding production');
  }
  const adminPasswordHash = hashPassword(adminPassword);
  const tenantPasswordHash = hashPassword(tenantPassword);

  console.log('Seeding RMS demo data…');

  // ── Organization ──────────────────────────────────────────
  const org = await prisma.organization.upsert({
    where: { code: 'MAIN' },
    update: {},
    create: {
      code: 'MAIN',
      name: 'Demo Property Co.',
      nameZh: '示範物業有限公司',
      address: 'Central, Hong Kong',
      email: 'office@demo.rms',
    },
  });

  // ── Settings (business config that used to be hardcoded) ──
  const settings: Record<string, unknown> = {
    currency: 'HKD',
    'currency.symbol': 'HK$',
    timezone: 'Asia/Hong_Kong',
    'locale.default': 'zh-HK',
    'invoice.issue_day_of_month': 1,
    'invoice.due_day_of_month': 10,
    'invoice.first_due_offset_days': 9,
    'invoice.auto_issue': false,
    'deposit.default_months': 2,
    'interest.default_policy_code': '',
    'brand.name': 'Demo Property Co.',
    // Days either side of a master meter's date a sub-meter reading may fall and
    // still be deducted from that bill (metering/sub-meter-deduction.ts).
    'metering.sub_meter_tolerance_days': 7,
  };
  for (const [key, value] of Object.entries(settings)) {
    await prisma.setting.upsert({
      where: { organizationId_key: { organizationId: org.id, key } },
      update: { value: value as never },
      create: { organizationId: org.id, key, value: value as never },
    });
  }

  // ── Chart of accounts ─────────────────────────────────────
  // On the office's ERP codes; the rest of their chart is imported from the
  // ERP's export on the Chart of Accounts page. Created when missing and never
  // overwritten, because codes and names are the office's to change there — so
  // the system's own accounts are matched by role, which is how the ledger
  // finds them, and the others by code.
  const glDefs = [
    { code: '1200-01-0000', name: '應收賬項 (Accounts Receivable)', type: 'ASSET' as const, role: 'RECEIVABLE' as const },
    { code: '1000', name: 'Bank', type: 'ASSET' as const, role: 'BANK' as const, isBank: true },
    { code: '7120-01-0000', name: '租務收入(Rental Income)', type: 'INCOME' as const },
    { code: '7130-01-0000', name: '行政管理費收入 (Management Fee Income)', type: 'INCOME' as const },
    { code: '2100', name: 'Rates Payable', type: 'LIABILITY' as const },
    { code: '2200', name: 'Utilities Clearing', type: 'LIABILITY' as const },
    { code: '4070-01-0000', name: "暫收費用-租務按金 (Dep rec'd in adv.-Rental Dep)", type: 'LIABILITY' as const, role: 'DEPOSITS_HELD' as const },
    { code: '2310', name: 'Refunds Payable', type: 'LIABILITY' as const, role: 'REFUNDS_PAYABLE' as const },
    { code: '4050-01-0000', name: '預收費用 (Cash in Advance)', type: 'LIABILITY' as const, role: 'TENANT_CREDIT' as const },
    { code: '2400', name: 'Stamp Duty Payable', type: 'LIABILITY' as const },
    { code: '7700-03-0000', name: '其他利息收入(Other Interest Income)', type: 'INCOME' as const },
    { code: '8180-99-0000', name: '維修費-其他項目 (R&M-Others)', type: 'EXPENSE' as const },
  ];
  const gl: Record<string, string> = {};
  for (const g of glDefs) {
    const found = await prisma.glAccount.findFirst({
      where: { organizationId: org.id, ...('role' in g ? { role: g.role } : { code: g.code }) },
      select: { id: true },
    });
    gl[g.code] = (found ?? (await prisma.glAccount.create({ data: { organizationId: org.id, ...g } }))).id;
  }

  // ── Charge types (replaces legacy magic numbers 0–23) ─────
  const chargeDefs = [
    // `waived`: a lease's rent-free window frees the rent and nothing else —
    // the office can move that line on the Charge Types screen afterwards, for
    // every category but UTILITY: water, electricity and gas are billed on what
    // the meter says was used, and the Charge Types screen refuses the pair.
    { code: 'RENT', nameEn: 'Rent', nameZh: '租金', category: 'RECURRING' as const, gl: '7120-01-0000', system: true, waived: true },
    { code: 'MGMT_FEE', nameEn: 'Management Fee', nameZh: '管理費', category: 'RECURRING' as const, gl: '7130-01-0000' },
    { code: 'RATES', nameEn: 'Government Rates', nameZh: '差餉', category: 'RECURRING' as const, gl: '2100' },
    { code: 'GOV_RENT', nameEn: 'Government Rent', nameZh: '地租', category: 'RECURRING' as const, gl: '2100' },
    { code: 'WATER', nameEn: 'Water', nameZh: '水費', category: 'UTILITY' as const, gl: '2200' },
    { code: 'ELECTRICITY', nameEn: 'Electricity', nameZh: '電費', category: 'UTILITY' as const, gl: '2200' },
    { code: 'GAS', nameEn: 'Gas', nameZh: '煤氣', category: 'UTILITY' as const, gl: '2200' },
    { code: 'RENT_DEPOSIT', nameEn: 'Rent Deposit', nameZh: '租金按金', category: 'DEPOSIT' as const, gl: '4070-01-0000', system: true },
    { code: 'MGMT_DEPOSIT', nameEn: 'Management Fee Deposit', nameZh: '管理費按金', category: 'DEPOSIT' as const, gl: '4070-01-0000' },
    { code: 'STAMP_DUTY', nameEn: 'Stamp Duty', nameZh: '印花稅', category: 'ONE_OFF' as const, gl: '2400' },
    { code: 'RM', nameEn: 'Repairs & Maintenance', nameZh: '維修', category: 'ONE_OFF' as const, gl: '8180-99-0000' },
    { code: 'CONCESSION', nameEn: 'Rent Concession', nameZh: '租金優惠', category: 'ADJUSTMENT' as const, gl: '7120-01-0000' },
    { code: 'LATE_INTEREST', nameEn: 'Late Interest', nameZh: '逾期利息', category: 'ADJUSTMENT' as const, gl: '7700-03-0000', system: true },
  ];
  let sort = 0;
  for (const c of chargeDefs) {
    await prisma.chargeType.upsert({
      where: { organizationId_code: { organizationId: org.id, code: c.code } },
      update: { nameEn: c.nameEn, nameZh: c.nameZh, category: c.category },
      create: {
        organizationId: org.id,
        code: c.code,
        nameEn: c.nameEn,
        nameZh: c.nameZh,
        category: c.category,
        glAccountId: gl[c.gl],
        isSystem: c.system ?? false,
        // Create only, never on update, like the account above: the flag is
        // configuration the office owns, and re-running the seed must not undo
        // a choice it has made.
        waivedDuringRentFree: c.waived ?? false,
        sortOrder: sort++,
      },
    });
  }

  // ── Interest policy (default OFF per agreed rules) ────────
  await prisma.interestPolicy.upsert({
    where: { organizationId_code: { organizationId: org.id, code: 'STANDARD' } },
    update: {},
    create: {
      organizationId: org.id,
      code: 'STANDARD',
      name: 'Standard 2%/month',
      ratePercent: '2.000000',
      dayCountBasis: 'ACTUAL_DAYS_IN_MONTH',
      graceDays: 0,
      isActive: false,
    },
  });

  // ── Settlement methods ────────────────────────────────────
  const settleDefs = [
    { code: 'CASH', nameEn: 'Cash', nameZh: '現金', ref: false },
    { code: 'CHEQUE', nameEn: 'Cheque', nameZh: '支票', ref: true, remark: 'Cheque deposit (Not valid until cheque is cleared)' },
    { code: 'BANK_TRANSFER', nameEn: 'Bank Transfer', nameZh: '銀行轉帳', ref: true },
    { code: 'FPS', nameEn: 'FPS', nameZh: '轉數快', ref: true },
    { code: 'AUTOPAY', nameEn: 'Autopay', nameZh: '自動轉帳', ref: false },
  ];
  let ssort = 0;
  for (const s of settleDefs) {
    await prisma.settlementMethod.upsert({
      where: { code: s.code },
      // Empty on purpose: these are editable in the admin now, so re-seeding
      // must not silently revert a rename or a requiresReference the office set.
      update: {},
      create: { code: s.code, nameEn: s.nameEn, nameZh: s.nameZh, requiresReference: s.ref, receiptRemark: 'remark' in s ? s.remark : null, sortOrder: ssort++ },
    });
  }

  // ── Reference values (regions / categories / lease types) ─
  const refDefs = [
    { domain: 'REGION' as const, code: 'HK_ISLAND', en: 'Hong Kong Island', zh: '香港島' },
    { domain: 'REGION' as const, code: 'KOWLOON', en: 'Kowloon', zh: '九龍' },
    { domain: 'REGION' as const, code: 'NEW_TERRITORIES', en: 'New Territories', zh: '新界' },
    { domain: 'PROPERTY_CATEGORY' as const, code: 'RESIDENTIAL', en: 'Residential', zh: '住宅' },
    { domain: 'PROPERTY_CATEGORY' as const, code: 'COMMERCIAL', en: 'Commercial', zh: '商業' },
    { domain: 'PROPERTY_CATEGORY' as const, code: 'INDUSTRIAL', en: 'Industrial', zh: '工業' },
    { domain: 'PROPERTY_CATEGORY' as const, code: 'GOVERNMENT', en: 'Government, Public & Special Property', zh: '政府及公共或特殊物業' },
    { domain: 'LEASE_TYPE' as const, code: 'FIXED_TERM', en: 'Fixed Term', zh: '固定租期' },
    { domain: 'LEASE_TYPE' as const, code: 'PERIODIC', en: 'Periodic', zh: '週期性' },
    // What the premises are let for — the office maintains this list itself.
    { domain: 'LEASE_USAGE' as const, code: 'RESIDENTIAL', en: 'Residential', zh: '住宅' },
    { domain: 'LEASE_USAGE' as const, code: 'OFFICE', en: 'Office', zh: '寫字樓' },
    { domain: 'LEASE_USAGE' as const, code: 'FACTORY', en: 'Factory', zh: '工廠' },
    { domain: 'LEASE_USAGE' as const, code: 'WAREHOUSE', en: 'Warehouse', zh: '倉庫' },
    { domain: 'LEASE_USAGE' as const, code: 'RETAIL', en: 'Retail Shop', zh: '商舖' },
    { domain: 'LEASE_USAGE' as const, code: 'OTHER', en: 'Other', zh: '其他' },
    { domain: 'AMENITY' as const, code: 'AIRCON', en: 'Air Conditioning', zh: '冷氣' },
    { domain: 'AMENITY' as const, code: 'PARKING', en: 'Parking', zh: '車位' },
    // Maintenance taxonomy — user-configurable, not hardcoded (replaces the
    // legacy's numeric-string priority/category baked into PHP controllers).
    { domain: 'MAINTENANCE_CATEGORY' as const, code: 'PLUMBING', en: 'Plumbing', zh: '水喉' },
    { domain: 'MAINTENANCE_CATEGORY' as const, code: 'ELECTRICAL', en: 'Electrical', zh: '電器' },
    { domain: 'MAINTENANCE_CATEGORY' as const, code: 'HVAC', en: 'Air Conditioning', zh: '冷氣' },
    { domain: 'MAINTENANCE_CATEGORY' as const, code: 'APPLIANCE', en: 'Appliance', zh: '電器設備' },
    { domain: 'MAINTENANCE_CATEGORY' as const, code: 'STRUCTURAL', en: 'Structural', zh: '結構' },
    { domain: 'MAINTENANCE_CATEGORY' as const, code: 'PEST', en: 'Pest Control', zh: '滅蟲' },
    { domain: 'MAINTENANCE_CATEGORY' as const, code: 'OTHER', en: 'Other', zh: '其他' },
    { domain: 'MAINTENANCE_PRIORITY' as const, code: 'LOW', en: 'Low', zh: '低' },
    { domain: 'MAINTENANCE_PRIORITY' as const, code: 'NORMAL', en: 'Normal', zh: '一般' },
    { domain: 'MAINTENANCE_PRIORITY' as const, code: 'HIGH', en: 'High', zh: '緊急' },
    { domain: 'MAINTENANCE_PRIORITY' as const, code: 'URGENT', en: 'Urgent', zh: '特急' },
    // What a letter to a property was about — the notice/letter log's own list,
    // maintained by the office on the Option Lists screen from here on.
    { domain: 'NOTICE_TYPE' as const, code: 'MGMT_FEE_ADJUSTMENT', en: 'Management Fee Adjustment', zh: '管理費調整' },
    { domain: 'NOTICE_TYPE' as const, code: 'CONTRIBUTION', en: 'Contribution', zh: '攤分費用' },
    { domain: 'NOTICE_TYPE' as const, code: 'OTHERS', en: 'Others', zh: '其他' },
    // The purchase paperwork the office files against a building — the eight
    // kinds their spreadsheet lists. A classification, not a slot: several title
    // deeds on one property are normal, and the list is theirs to extend.
    { domain: 'PROPERTY_DOCUMENT_TYPE' as const, code: 'PASP', en: 'Provisional Agreement for Sale and Purchase', zh: '臨時買賣合約' },
    { domain: 'PROPERTY_DOCUMENT_TYPE' as const, code: 'SPA', en: 'Formal Agreement for Sale and Purchase', zh: '正式買賣合約' },
    { domain: 'PROPERTY_DOCUMENT_TYPE' as const, code: 'ASSIGNMENT', en: 'Assignment / Sale Deed', zh: '轉讓契／賣契' },
    { domain: 'PROPERTY_DOCUMENT_TYPE' as const, code: 'LAND_SEARCH', en: 'Land Search Record', zh: '土地查冊記錄' },
    { domain: 'PROPERTY_DOCUMENT_TYPE' as const, code: 'TITLE_DEEDS', en: 'Title Deeds', zh: '樓契' },
    { domain: 'PROPERTY_DOCUMENT_TYPE' as const, code: 'FLOOR_PLAN', en: 'Floor Plan', zh: '樓面平面圖' },
    { domain: 'PROPERTY_DOCUMENT_TYPE' as const, code: 'MORTGAGE_DEED', en: 'Mortgage Deed', zh: '按揭契' },
    { domain: 'PROPERTY_DOCUMENT_TYPE' as const, code: 'APPORTIONMENT', en: 'Settlement of Apportionment Account', zh: '分攤帳目結算書' },
    // What a file behind a repair is — the evidence that goes onto the debit
    // note charging it. The office's list, as above.
    { domain: 'MAINTENANCE_DOCUMENT_TYPE' as const, code: 'REPAIR_SLIP', en: 'Repair Slip', zh: '維修單' },
    { domain: 'MAINTENANCE_DOCUMENT_TYPE' as const, code: 'BANK_IN_RECEIPT', en: 'Bank-in Receipt', zh: '入數收據' },
    { domain: 'MAINTENANCE_DOCUMENT_TYPE' as const, code: 'SUPPLIER_RECEIPT', en: 'Supplier Receipt', zh: '供應商收據' },
    { domain: 'MAINTENANCE_DOCUMENT_TYPE' as const, code: 'OTHER', en: 'Other', zh: '其他' },
    // Where a property is — picks its landlord's local contact for the letterhead.
    { domain: 'COUNTRY' as const, code: 'HK', en: 'Hong Kong', zh: '香港' },
    { domain: 'COUNTRY' as const, code: 'SG', en: 'Singapore', zh: '新加坡' },
  ];
  let rsort = 0;
  for (const r of refDefs) {
    await prisma.referenceValue.upsert({
      where: { organizationId_domain_code: { organizationId: org.id, domain: r.domain, code: r.code } },
      // Empty on purpose: the maintenance taxonomy is editable in the admin
      // now, so re-seeding must not revert a rename the office made.
      update: {},
      create: { organizationId: org.id, domain: r.domain, code: r.code, nameEn: r.en, nameZh: r.zh, sortOrder: rsort++ },
    });
  }

  // ── Permissions & roles (RBAC as data) ────────────────────
  const resourceKeys = [
    'property', 'unit', 'lease', 'invoice', 'receipt', 'deposit', 'tenant',
    'landlord', 'charge-type', 'gl-account', 'interest-policy', 'settlement-method', 'reference-value', 'bank-account',
    'approval-workflow', 'role', 'setting', 'meter-reading', 'maintenance', 'notice',
  ];
  const actions = ['read', 'create', 'update', 'delete'];
  const permIds: string[] = [];
  for (const res of resourceKeys) {
    for (const act of actions) {
      const key = `${res}.${act}`;
      const p = await prisma.permission.upsert({
        where: { key },
        update: {},
        create: { key, description: `${act} ${res}` },
      });
      permIds.push(p.id);
    }
  }
  // Special permissions
  for (const key of ['invoice.approve', 'tenant.view-id-number', 'finance.report', 'audit.read', 'master-data.export']) {
    const p = await prisma.permission.upsert({ where: { key }, update: {}, create: { key } });
    permIds.push(p.id);
  }

  const adminRole = await prisma.role.upsert({
    where: { code: 'ADMIN' },
    update: {},
    create: { code: 'ADMIN', name: 'Administrator', nameZh: '管理員', isSystem: true },
  });
  const staffRole = await prisma.role.upsert({
    where: { code: 'STAFF' },
    update: {},
    create: { code: 'STAFF', name: 'Staff', nameZh: '職員', isSystem: true },
  });
  const tenantRole = await prisma.role.upsert({
    where: { code: 'TENANT' },
    update: {},
    create: { code: 'TENANT', name: 'Tenant', nameZh: '租客', isSystem: true },
  });

  // Admin gets every permission.
  await prisma.rolePermission.deleteMany({ where: { roleId: adminRole.id } });
  await prisma.rolePermission.createMany({
    data: permIds.map((permissionId) => ({ roleId: adminRole.id, permissionId })),
  });

  // STAFF is a functional day-to-day operator: all reads + create/update on
  // operational resources, but no deletes, no config/role/setting management,
  // and none of the sensitive actions (invoice.approve, tenant id number, etc.).
  const staffOps = ['invoice', 'receipt', 'deposit', 'maintenance', 'meter-reading', 'lease', 'tenant', 'property', 'notice'];
  const staffPerms = await prisma.permission.findMany({
    where: {
      // "All reads" excludes the two administrative families, or the sentence
      // above is not true: role.read and setting.read both end in .read, and
      // they are what put Roles, Users and Settings in front of a clerk.
      NOT: [{ key: { startsWith: 'role.' } }, { key: { startsWith: 'setting.' } }],
      OR: [
        { key: { endsWith: '.read' } },
        { key: { in: staffOps.flatMap((r) => [`${r}.create`, `${r}.update`]) } },
      ],
    },
    select: { id: true },
  });
  await prisma.rolePermission.deleteMany({ where: { roleId: staffRole.id } });
  await prisma.rolePermission.createMany({
    data: staffPerms.map((p) => ({ roleId: staffRole.id, permissionId: p.id })),
  });

  // ── Department roles ──────────────────────────────────────
  // The two departments that actually run the debit-note workflow: Leasing
  // raises and reviews, Accounting signs off. They hold every operational
  // permission — they are separated by *who* they are (the workflow routes
  // step 1 / step 2 by role), not by what they can do — but not the two
  // administrative families: `setting.` is the organisation's own configuration,
  // and `role.` is what gates the Roles and Users screens, which is an
  // administrator's job rather than a department's.
  const deptRoleDefs = [
    { code: 'LEASING', name: 'Leasing', nameZh: '租賃部' },
    { code: 'ACCOUNTING', name: 'Accounting', nameZh: '會計部' },
  ];
  const deptPerms = await prisma.permission.findMany({
    where: { NOT: { OR: [{ key: { startsWith: 'setting.' } }, { key: { startsWith: 'role.' } }] } },
    select: { id: true },
  });
  const dept: Record<string, string> = {};
  for (const d of deptRoleDefs) {
    const role = await prisma.role.upsert({
      where: { code: d.code },
      update: { name: d.name, nameZh: d.nameZh },
      create: { code: d.code, name: d.name, nameZh: d.nameZh },
    });
    dept[d.code] = role.id;
    await prisma.rolePermission.deleteMany({ where: { roleId: role.id } });
    await prisma.rolePermission.createMany({
      data: deptPerms.map((p) => ({ roleId: role.id, permissionId: p.id })),
    });
  }

  // ── Number sequences ──────────────────────────────────────
  const seqDefs = [
    { docType: 'INVOICE', prefix: 'DN-' },
    { docType: 'RECEIPT', prefix: 'RE-' },
    { docType: 'DEPOSIT', prefix: 'DEP-' },
    { docType: 'DEPOSIT_RECEIPT', prefix: 'DR-' },
    { docType: 'LEASE', prefix: 'L-' },
    // P-WF240301: the company, the year and month the purchase completed.
    { docType: 'PROPERTY', prefix: 'P-', parts: 'SYMBOL,COMPANY,YEAR,MONTH,SERIAL', padding: 2, resetPeriod: 'MONTHLY' },
  ];
  for (const s of seqDefs) {
    await prisma.numberSequence.upsert({
      where: { organizationId_docType: { organizationId: org.id, docType: s.docType } },
      update: {},
      create: { organizationId: org.id, padding: 6, ...s },
    });
  }

  // ── Admin login ───────────────────────────────────────────
  await prisma.user.upsert({
    where: { email: 'admin@rms.local' },
    update: process.env.SEED_ADMIN_PASSWORD ? { passwordHash: adminPasswordHash } : {},
    create: {
      email: 'admin@rms.local',
      name: 'Administrator',
      passwordHash: adminPasswordHash,
      locale: 'en',
      roles: { create: { roleId: adminRole.id } },
    },
  });

  // Utility rates are not seeded: each property sets its own on the Metering
  // page, and the seed creates no properties.

  // ── Tenant-portal demo login ──────────────────────────────
  // A tenant party is required for a portal login to hang off; properties,
  // leases and debit notes are created by the users, not seeded.
  let tenant = await prisma.tenant.findFirst({ where: { organizationId: org.id, name: 'Chan Tai Man' } });
  if (!tenant) {
    tenant = await prisma.tenant.create({
      data: { organizationId: org.id, name: 'Chan Tai Man', nameZh: '陳大文', email: 'tenant@demo.rms', phone: '+85290000000' },
    });
  }

  // Tenant portal login, linked to the tenant party.
  await prisma.user.upsert({
    where: { email: 'tenant@rms.local' },
    update: {
      tenantId: tenant.id,
      ...(process.env.SEED_TENANT_PASSWORD ? { passwordHash: tenantPasswordHash } : {}),
    },
    create: {
      email: 'tenant@rms.local',
      name: 'Chan Tai Man',
      passwordHash: tenantPasswordHash,
      locale: 'zh-HK',
      tenantId: tenant.id,
      roles: { create: { roleId: tenantRole.id } },
    },
  });

  // ── Notification templates (data, user-editable) + settings ───────────────
  await prisma.setting.upsert({
    where: { organizationId_key: { organizationId: org.id, key: 'notification.enabled' } },
    update: {},
    create: { organizationId: org.id, key: 'notification.enabled', value: true },
  });
  await prisma.setting.upsert({
    where: { organizationId_key: { organizationId: org.id, key: 'notification.staff_email' } },
    update: {},
    create: { organizationId: org.id, key: 'notification.staff_email', value: 'staff@rms.local' },
  });
  const templateDefs = [
    { event: 'INVOICE_ISSUED' as const, subject: '您的帳單 {{invoiceNumber}}', body: '親愛的 {{tenantName}}，您的帳單 {{invoiceNumber}}（{{period}}）金額 {{amount}}，到期日 {{dueDate}}。請準時繳付，多謝。' },
    { event: 'RECEIPT_APPROVED' as const, subject: '已收到您的付款', body: '{{tenantName}} 您好，我們已確認收到您的付款 {{receiptNumber}}，金額 {{amount}}（{{date}}）。多謝。' },
    { event: 'RECEIPT_REJECTED' as const, subject: '您的付款未獲接納', body: '{{tenantName}} 您好，您就 {{receiptNumber}}（{{amount}}）提交的付款未獲接納。原因：{{reason}}。如有疑問請與我們聯絡。' },
    { event: 'RECEIPT_BOUNCED' as const, subject: '付款未能過數', body: '{{tenantName}} 您好，您的付款 {{receiptNumber}}（{{amount}}）未能過數，請盡快重新安排付款。' },
    { event: 'MAINTENANCE_STATUS_CHANGED' as const, subject: '維修進度更新', body: '{{tenantName}} 您好，您的維修申請「{{title}}」（{{property}} {{unit}}）狀態已更新為 {{status}}。' },
    { event: 'STATEMENT_SENT' as const, subject: '您的月結單（{{period}}）', body: '{{tenantName}} 您好，租約 {{leaseReference}} {{period}} 的月結單已上載到租客網頁，結欠 {{balance}}。請登入查閱，多謝。' },
  ];
  for (const t of templateDefs) {
    await prisma.notificationTemplate.upsert({
      where: {
        organizationId_event_channel_locale_recipient: {
          organizationId: org.id,
          event: t.event,
          channel: 'EMAIL',
          locale: 'zh',
          recipient: 'TENANT',
        },
      },
      update: { subject: t.subject, body: t.body },
      create: { organizationId: org.id, event: t.event, channel: 'EMAIL', locale: 'zh', recipient: 'TENANT', subject: t.subject, body: t.body },
    });
  }

  // ── Debit-note approval workflow ──────────────────────────
  // No threshold: every debit note is reviewed by Leasing then signed off by
  // Accounting before it can be issued.
  const hasWorkflow = await prisma.approvalWorkflow.findFirst({
    where: { organizationId: org.id, documentType: 'INVOICE', code: 'debitnote' },
  });
  if (!hasWorkflow) {
    await prisma.approvalWorkflow.create({
      data: {
        organizationId: org.id,
        documentType: 'INVOICE',
        code: 'debitnote',
        name: 'Debit Note',
        minAmount: null,
        isActive: true,
        steps: {
          create: [
            { stepOrder: 1, name: 'Leasing review', actorType: 'ROLE', actorRoleId: dept['LEASING'] },
            { stepOrder: 2, name: 'Accounting sign-off', actorType: 'ROLE', actorRoleId: dept['ACCOUNTING'] },
          ],
        },
      },
    });
  }

  console.log('Seed complete:');
  console.log(`  org=${org.code}  charge_types=${chargeDefs.length}  gl_accounts=${glDefs.length}`);
  console.log(`  settlement_methods=${settleDefs.length}  permissions=${permIds.length}  roles=5 (ADMIN, STAFF, TENANT, LEASING, ACCOUNTING)`);
  console.log(`  approval: "Debit Note" — every DN, Leasing → Accounting`);
  console.log(`  admin login: admin@rms.local / ${process.env.SEED_ADMIN_PASSWORD ? '<configured password>' : 'admin123'}`);
  console.log(`  no properties, leases or debit notes are seeded — create them in the app.`);
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(() => prisma.$disconnect());
