/**
 * Imports the group's landlord companies.
 *
 * These 20 rows are the owner's master data, not demo data, which is why they
 * are here and not in prisma/seed.ts: a seed runs on every UAT reset and on a
 * fresh install, and neither should conjure another company's real companies.
 *
 * Idempotent — matched on (organizationId, code), so running it again after the
 * office has renamed one, or after the list has grown, updates rather than
 * duplicates. Nothing is deleted: a company that disappears from this list is
 * left alone, because a property may already point at it.
 *
 * `accountCode` is the company's account in the ERP, named by its code: the
 * import links the landlord to that account in the chart of accounts, adding
 * it to the chart if the ERP's export has not been imported yet. Nothing in the
 * ledger posts to it (see the schema comment on Landlord).
 *
 * Run: cd apps/api && npm run import:landlords
 */
import { PrismaClient } from '@prisma/client';
import { accountCode as checkedAccountCode, accountTypeFor, landlordCode } from '../src/common/codes';

export interface LandlordRow {
  code: string;
  name: string;
  accountCode?: string | null;
}

/** Exactly as the office's spreadsheet has them. "Limtied" on the last row is
 *  their spelling of their own company — their data, not a typo to fix here. */
export const LANDLORDS: LandlordRow[] = [
  { code: 'AL', name: 'All Link International Limited', accountCode: '1810-13-0000' },
  { code: 'BP', name: 'Blossom Properties Limited', accountCode: '1810-46-0000' },
  { code: 'CT', name: 'Chain Tech International Limited', accountCode: '1810-02-0000' },
  { code: 'DI', name: 'Dimension Development Limited', accountCode: '1830-31-0000' },
  { code: 'DP', name: 'Dynamic Properties Limited', accountCode: '1810-45-0000' },
  { code: 'EU', name: 'East Union Industries Limited', accountCode: '1800-31-0000' },
  { code: 'GN', name: 'Golden National Limited', accountCode: '1810-16-0000' },
  { code: 'JE', name: 'Joy East Limited', accountCode: '1800-24-0000' },
  { code: 'LE', name: 'Luck Elegant Industrial Limited', accountCode: '1810-14-0000' },
  { code: 'LF', name: 'Lucky Forever Limited', accountCode: '1810-35-0000' },
  { code: 'NP', name: 'NP Development Limited', accountCode: '1810-39-0000' },
  { code: 'PD', name: 'Precious Development Limited', accountCode: '1830-33-0000' },
  { code: 'PR', name: 'Precise Development Limited', accountCode: '1830-32-0000' },
  { code: 'QE', name: 'Queen Express Limited', accountCode: '1810-40-0000' },
  { code: 'SX', name: 'Senex Investments Limited', accountCode: '1810-10-0000' },
  { code: 'UI', name: 'United Industries Limited', accountCode: '1810-11-0000' },
  { code: 'VD', name: 'Victor Development Limited', accountCode: '1810-38-0000' },
  { code: 'WF', name: 'Well Faith International Enterprise Limited', accountCode: '1800-32-0000' },
  { code: 'WW', name: 'Wise World Limited', accountCode: '1800-25-0000' },
  { code: 'YL', name: 'Yes Link (Asia) Limtied', accountCode: '1810-41-0000' },
];

/** The chart's account for an ERP code, added when the chart lacks it — named
 *  after the company, as the ERP names a company's current account, until the
 *  ERP's own export is imported over it. */
async function accountFor(prisma: PrismaClient, organizationId: string, code: string, name: string): Promise<string> {
  const found = await prisma.glAccount.findFirst({ where: { organizationId, code }, select: { id: true } });
  if (found) return found.id;
  return (await prisma.glAccount.create({ data: { organizationId, code, name, type: accountTypeFor(code) } })).id;
}

export interface ImportResult {
  created: string[];
  updated: string[];
  unchanged: string[];
}

/**
 * Upserts the rows by (organizationId, code). Exported so the smoke can run it
 * twice over a fixture and prove a second run changes nothing — the property of
 * this script that matters, since it will be re-run every time the list grows.
 *
 * Only `name` and `accountCode` are the spreadsheet's to own. Anything the
 * office later types in the admin — the Chinese name, the address, the phone,
 * whether it is still active — is left untouched, or an import would quietly
 * undo their work.
 */
export async function importLandlords(
  prisma: PrismaClient,
  organizationId: string,
  rows: LandlordRow[],
  startSortOrder = 0,
): Promise<ImportResult> {
  const result: ImportResult = { created: [], updated: [], unchanged: [] };
  let sortOrder = startSortOrder;
  for (const row of rows) {
    const code = landlordCode(row.code);
    const accountCode = checkedAccountCode(row.accountCode) ?? null;
    const glAccountId = accountCode ? await accountFor(prisma, organizationId, accountCode, row.name) : null;
    const existing = await prisma.landlord.findFirst({
      where: { organizationId, code },
      select: { id: true, name: true, glAccountId: true },
    });
    if (!existing) {
      await prisma.landlord.create({
        data: { organizationId, code, name: row.name, glAccountId, sortOrder: sortOrder++ },
      });
      result.created.push(code);
      continue;
    }
    sortOrder++;
    if (existing.name === row.name && existing.glAccountId === glAccountId) {
      result.unchanged.push(code);
      continue;
    }
    await prisma.landlord.update({ where: { id: existing.id }, data: { name: row.name, glAccountId } });
    result.updated.push(code);
  }
  return result;
}

async function main(): Promise<void> {
  const prisma = new PrismaClient();
  try {
    // Single-org system: the one organisation is resolved exactly as the rest of
    // the app resolves it.
    const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true, code: true } });
    if (!org) throw new Error('No organisation found — run the seed first');

    const result = await importLandlords(prisma, org.id, LANDLORDS);
    console.log(`Landlords imported into org ${org.code}:`);
    console.log(`  created   ${result.created.length}${result.created.length ? `  (${result.created.join(', ')})` : ''}`);
    console.log(`  updated   ${result.updated.length}${result.updated.length ? `  (${result.updated.join(', ')})` : ''}`);
    console.log(`  unchanged ${result.unchanged.length}${result.unchanged.length ? `  (${result.unchanged.join(', ')})` : ''}`);
  } finally {
    await prisma.$disconnect();
  }
}

// Only when run as a script: the smoke imports importLandlords() from here.
if (require.main === module) {
  main().catch((e) => {
    console.error(e);
    process.exit(1);
  });
}
