import type { PrismaClient } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { PRE_ISSUE_STATUSES } from '../../billing/invoice-status';
import { parseDay } from '../../common/hk-date';
import { buildingKey, buildingOf, checkLeaseUnits, leaseBuilding, propertiesOf } from '../../common/lease-premises';
import { assignNumber } from '../../common/number.service';
import { prefillForLease, standardFigures } from '../../standard-charges/standard-charge.service';
import { findReferenceValue, referenceOptions } from '../reference-lookup';
import { router, withPermission } from '../trpc';

/** A unit's billing group as stored: trimmed, and none when blank. */
const groupOf = (groups: Record<string, string>, unitId: string): string | null => groups[unitId]?.trim() || null;

const chargeRuleInput = z.object({
  chargeTypeId: z.string(),
  amount: z.string().regex(/^\d+(\.\d{1,2})?$/, 'Enter a valid amount'),
  frequencyMonths: z.number().int().min(0).default(1),
  timing: z.enum(['ADVANCE', 'ARREARS']).default('ADVANCE'),
  proration: z.enum(['DAILY', 'FULL_MONTH']).default('DAILY'),
  firstInvoiceOnly: z.boolean().default(false),
  unitId: z.string().optional().nullable(),
  // A rule that only applies for part of the term — how a stepped rent is
  // expressed: one rule per step, each bounded to its own years. The engine has
  // always clipped to these; until now nothing could write them.
  startDate: z.string().optional().nullable(),
  endDate: z.string().optional().nullable(),
  /** Billed at the property's standard charge as in force on each day, not at
   *  `amount` (standard-charges/standard-billing.ts). */
  followsStandard: z.boolean().default(false),
});

/** Only a recurring charge has a standard figure to follow: a one-off one is
 *  billed once, at what was agreed. */
function checkFollowing(rules: readonly { followsStandard: boolean; frequencyMonths: number; firstInvoiceOnly: boolean }[]): void {
  if (rules.some((r) => r.followsStandard && (r.frequencyMonths < 1 || r.firstInvoiceOnly))) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'A one-off charge cannot follow the standard charge' });
  }
}

// A lease whose term has passed is effectively ENDED even before the nightly
// transition job flips the stored flag — derive it on read so the UI never shows
// a finished lease as still active (the same "derive, don't store" rule we use
// for balances). Mirrors billing.transitionLeases' predicate (endDate < now) so
// the display and the eventual stored flip never disagree. The stored status
// stays the source of truth for billing, which reconciles it before every run.
function displayStatus(status: string, endDate: Date, now: Date): string {
  return status === 'ACTIVE' && endDate.getTime() < now.getTime() ? 'ENDED' : status;
}

const leaseInput = z.object({
  reference: z.string().optional(),
  tenantId: z.string(),
  status: z.enum(['DRAFT', 'ACTIVE', 'ENDED', 'TERMINATED']).default('ACTIVE'),
  currency: z.enum(['HKD', 'SGD']).default('HKD'),
  startDate: z.string(),
  endDate: z.string(),
  dueDayOfMonth: z.number().int().min(1).max(31).optional().nullable(),
  /** Which account this tenancy pays into. Null falls back to the
   *  organisation's collection account when the note is issued. */
  bankAccountId: z.string().optional().nullable(),
  depositMonths: z.number().int().min(0).default(0),
  /** The one rent-free window this tenancy was signed with — a fit-out period,
   *  or free months. Both dates or neither; see checkRentFree. */
  rentFreeFrom: z.string().optional().nullable(),
  rentFreeTo: z.string().optional().nullable(),
  /** Fixed term or periodic — reference_values (LEASE_TYPE). */
  leaseTypeId: z.string().optional().nullable(),
  /** What the premises are let for — reference_values (LEASE_USAGE). */
  usageId: z.string().optional().nullable(),
  /** Days' notice to renew or quit. Recorded only; nothing acts on it yet. */
  noticeDays: z.number().int().min(0).max(3650).optional().nullable(),
  note: z.string().optional().nullable(),
  renewedFromId: z.string().optional().nullable(),
  /** The premises: units of one building, from any of its purchases, of one
   *  landlord company (common/lease-premises.ts). */
  unitIds: z.array(z.string()).min(1, 'Choose at least one unit for the lease'),
  /** Each unit's billing group, by unit id: units with the same group go on one
   *  monthly note. Blank or left out is no group. */
  billingGroups: z.record(z.string(), z.string().max(20)).default({}),
  chargeRules: z.array(chargeRuleInput).default([]),
  /** Back-office tags. Names, not ids — the picker creates a label the first
   *  time it is used, so a typo is a new label rather than a silent no-op. */
  labels: z.array(z.string().min(1)).default([]),
});

/** The lease type and the usage are both reference values — same shape, same id
 *  space — so an id from the wrong list would store happily and read back as a
 *  blank name. Both are resolved against their own list, and this org's. */
async function checkLeaseTerms(
  prisma: PrismaClient,
  organizationId: string | undefined,
  leaseTypeId: string | null,
  usageId: string | null,
): Promise<void> {
  if (leaseTypeId && !(await findReferenceValue(prisma, organizationId, 'LEASE_TYPE', leaseTypeId))) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'Lease type not found' });
  }
  if (usageId && !(await findReferenceValue(prisma, organizationId, 'LEASE_USAGE', usageId))) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'Lease usage not found' });
  }
}

/** The rent-free window, checked against the term it belongs to.
 *
 *  Half a window is always a slip of the hand — one date without the other
 *  would silently free nothing — and a window that never touches the term is
 *  the same mistake made with two dates (usually last year's tenancy pasted in
 *  by accident). Both are refused rather than stored: billing would look
 *  correct while quietly charging the full rent. A window that runs past either
 *  end of the term IS allowed — "free until the 15th of the month you move in"
 *  is normally written from the 1st — the engine only ever frees the days a
 *  line actually covers.
 *
 *  Compared as parsed dates, not as strings, so the check cannot be defeated by
 *  a caller that sends a full ISO timestamp for one field and a plain date for
 *  the other. */
function checkRentFree(input: { startDate: string; endDate: string; rentFreeFrom?: string | null; rentFreeTo?: string | null }): void {
  const from = input.rentFreeFrom || null;
  const to = input.rentFreeTo || null;
  if (!from !== !to) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'A rent-free period needs both a start and an end date' });
  }
  if (!from || !to) return;
  const [f, t, s, e] = [from, to, input.startDate, input.endDate].map((d) => new Date(d).getTime());
  if (Number.isNaN(f) || Number.isNaN(t)) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'The rent-free period dates are not valid dates' });
  }
  if (f > t) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'The rent-free period cannot end before it starts' });
  }
  if (t < s || f > e) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'The rent-free period must overlap the lease term' });
  }
}

/** Resolves label names to ids, creating any that are new. Labels are a small
 *  shared vocabulary, so the same name always means the same label. */
async function syncLabels(
  db: { leaseLabel: { findMany: Function; create: Function }; leaseLabelOnLease: { deleteMany: Function; createMany: Function } },
  organizationId: string,
  leaseId: string,
  names: string[],
): Promise<void> {
  const wanted = [...new Set(names.map((n) => n.trim()).filter(Boolean))];
  await db.leaseLabelOnLease.deleteMany({ where: { leaseId } });
  if (wanted.length === 0) return;
  const existing = (await db.leaseLabel.findMany({ where: { organizationId, name: { in: wanted } }, select: { id: true, name: true } })) as { id: string; name: string }[];
  const byName = new Map(existing.map((l) => [l.name, l.id]));
  for (const name of wanted) {
    if (byName.has(name)) continue;
    const made = (await db.leaseLabel.create({ data: { organizationId, name } })) as { id: string };
    byName.set(name, made.id);
  }
  await db.leaseLabelOnLease.createMany({ data: wanted.map((n) => ({ leaseId, labelId: byName.get(n) as string })) });
}

export const leasesRouter = router({
  list: withPermission('lease.read')
    .input(z.object({ includeArchived: z.boolean().optional() }).optional())
    .query(async ({ ctx, input }) => {
      const rows = await ctx.prisma.lease.findMany({
        where: {
          organizationId: ctx.organizationId ?? undefined,
          ...(input?.includeArchived ? {} : { deletedAt: null }),
        },
        orderBy: { reference: 'asc' },
        include: {
          ...leaseBuilding,
          tenant: { select: { name: true } },
          labels: { include: { label: { select: { id: true, name: true } } } },
          _count: { select: { chargeRules: true, invoices: { where: { status: { not: 'VOID' } } } } },
        },
      });
      const now = new Date();
      return rows.map((l) => ({
        id: l.id,
        reference: l.reference,
        status: displayStatus(l.status, l.endDate, now),
        currency: l.currency,
        startDate: l.startDate,
        endDate: l.endDate,
        // Alongside the term, because a rent-free window is the reason a rent
        // line comes up short — and having to open each lease to find out which
        // ones have one is how the office ends up "checking" by re-reading the
        // contract.
        rentFreeFrom: l.rentFreeFrom,
        rentFreeTo: l.rentFreeTo,
        terminatedAt: l.terminatedAt,
        propertyName: buildingOf(propertiesOf(l.units)),
        tenantName: l.tenant.name,
        chargeRules: l._count.chargeRules,
        invoices: l._count.invoices,
        labels: l.labels.map((x) => ({ id: x.label.id, name: x.label.name })),
        archived: l.deletedAt != null,
      }));
    }),

  /** Everything a lease form needs: buildings (+their units), tenants, charge
   *  types, and the two term lists (fixed/periodic, and what it is let for).
   *
   *  A building is the properties sharing a name — each one purchase — and the
   *  form picks units from all of them. Every unit carries its purchase's
   *  company, so the form can keep a lease to one, and whether it is still
   *  offered: a sold or archived purchase's units are listed only so a lease
   *  already holding them can show them. */
  formData: withPermission('lease.read').query(async ({ ctx }) => {
    const org = ctx.organizationId ?? undefined;
    const [properties, tenants, chargeTypes, bankAccounts, leaseTypes, usages] = await Promise.all([
      ctx.prisma.property.findMany({
        where: { organizationId: org },
        orderBy: [{ name: 'asc' }, { code: 'asc' }],
        select: {
          id: true,
          name: true,
          code: true,
          deletedAt: true,
          saleCompletionDate: true,
          categoryId: true,
          landlord: { select: { id: true, code: true, name: true, nameZh: true } },
          units: { where: { deletedAt: null }, select: { id: true, name: true } },
        },
      }),
      ctx.prisma.tenant.findMany({ where: { organizationId: org, deletedAt: null }, orderBy: { name: 'asc' }, select: { id: true, name: true } }),
      // `waivedDuringRentFree` rides along so the form can name the charges a
      // rent-free window actually frees, instead of the user assuming "rent".
      ctx.prisma.chargeType.findMany({
        where: { organizationId: org, isActive: true },
        orderBy: { sortOrder: 'asc' },
        select: { id: true, code: true, nameEn: true, nameZh: true, waivedDuringRentFree: true },
      }),
      ctx.prisma.bankAccount.findMany({
        where: { organizationId: org, isActive: true },
        orderBy: [{ isCollectionAgent: 'desc' }, { name: 'asc' }],
        select: { id: true, name: true, bankName: true, accountNumber: true, isCollectionAgent: true },
      }),
      referenceOptions(ctx.prisma, org, 'LEASE_TYPE'),
      referenceOptions(ctx.prisma, org, 'LEASE_USAGE'),
    ]);
    const categories = new Map(
      (await ctx.prisma.referenceValue.findMany({ where: { organizationId: org, domain: 'PROPERTY_CATEGORY' }, select: { id: true, nameEn: true, nameZh: true } })).map(
        (c) => [c.id, c],
      ),
    );
    const units = properties.flatMap((p) => {
      const category = p.categoryId ? categories.get(p.categoryId) : undefined;
      return p.units.map((u) => ({
        id: u.id,
        name: u.name,
        building: p.name,
        propertyId: p.id,
        propertyCode: p.code,
        landlordId: p.landlord?.id ?? null,
        landlordCode: p.landlord?.code ?? null,
        landlordName: p.landlord?.name ?? null,
        landlordNameZh: p.landlord?.nameZh ?? null,
        categoryNameEn: category?.nameEn ?? null,
        categoryNameZh: category?.nameZh ?? null,
        available: !p.deletedAt && !p.saleCompletionDate,
      }));
    });
    const buildings = new Map<string, { key: string; name: string; units: typeof units }>();
    for (const u of units) {
      const key = buildingKey(u.building);
      if (!buildings.has(key)) buildings.set(key, { key, name: u.building, units: [] });
      buildings.get(key)!.units.push(u);
    }
    return { buildings: [...buildings.values()], tenants, chargeTypes, bankAccounts, leaseTypes, usages };
  }),

  /** The standard charges in force at this address on the tenancy's start date,
   *  shaped as ordinary charge rules the editor can change or drop before the
   *  lease is saved. A suggestion, never an instruction: nothing here writes
   *  anything, and a lease is saved from whatever is left on the form.
   *
   *  One rule per unit named on the lease — a per-unit rule is the only shape a
   *  split debit note can carry its own amount in — each at its own property's
   *  figure. */
  standardChargePrefill: withPermission('lease.read')
    .input(
      z.object({
        unitIds: z.array(z.string()).default([]),
        startDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Pick a start date'),
      }),
    )
    .query(async ({ ctx, input }) => ({
      onDate: input.startDate,
      rules: await prefillForLease(ctx.prisma, ctx.organizationId ?? '', input.unitIds, parseDay(input.startDate)),
      /** What a rule following the standard charges on that day, for the form
       *  to show beside it — per unit, and for the whole lease. */
      figures: await standardFigures(ctx.prisma, ctx.organizationId ?? '', input.unitIds, parseDay(input.startDate)),
    })),

  /** One charge rule made to follow the standard charge from now on — what the
   *  Management Fee Records page offers for a price kept apart. Its own amount
   *  stays, billed only where no standard figure covers it. */
  followStandard: withPermission('lease.update')
    .input(z.object({ ruleId: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const rule = await ctx.prisma.chargeRule.findFirst({
        where: { id: input.ruleId, lease: { organizationId: ctx.organizationId ?? '', deletedAt: null } },
        select: { id: true, frequencyMonths: true, firstInvoiceOnly: true },
      });
      if (!rule) throw new TRPCError({ code: 'NOT_FOUND', message: 'Charge rule not found' });
      checkFollowing([{ ...rule, followsStandard: true }]);
      await ctx.prisma.chargeRule.update({ where: { id: rule.id }, data: { followsStandard: true } });
      return { ok: true };
    }),

  get: withPermission('lease.read').input(z.object({ id: z.string() })).query(async ({ ctx, input }) => {
    const l = await ctx.prisma.lease.findFirst({
      where: { id: input.id, organizationId: ctx.organizationId ?? undefined },
      include: {
        units: { select: { unitId: true, billingGroup: true } },
        labels: { include: { label: { select: { name: true } } } },
        chargeRules: { orderBy: { sortOrder: 'asc' } },
      },
    });
    if (!l) throw new TRPCError({ code: 'NOT_FOUND' });
    const attachments = await ctx.prisma.attachment.findMany({
      where: { organizationId: ctx.organizationId ?? undefined, ownerType: 'LEASE', ownerId: l.id },
      orderBy: { createdAt: 'asc' },
      select: { id: true, filename: true, mimeType: true },
    });
    // The lease's own two terms, resolved WITHOUT the isActive filter the
    // pickers use: a value the office has since switched off is still this
    // lease's answer, and the form has to be able to name it rather than show
    // the record as blank while the id is quietly still there.
    const termIds = [l.leaseTypeId, l.usageId].filter((x): x is string => !!x);
    const terms = termIds.length
      ? await ctx.prisma.referenceValue.findMany({
          where: { id: { in: termIds } },
          select: { id: true, code: true, nameEn: true, nameZh: true },
        })
      : [];
    return {
      id: l.id,
      reference: l.reference,
      tenantId: l.tenantId,
      status: displayStatus(l.status, l.endDate, new Date()),
      currency: l.currency,
      startDate: l.startDate.toISOString().slice(0, 10),
      endDate: l.endDate.toISOString().slice(0, 10),
      dueDayOfMonth: l.dueDayOfMonth,
      bankAccountId: l.bankAccountId,
      depositMonths: l.depositMonths,
      rentFreeFrom: l.rentFreeFrom ? l.rentFreeFrom.toISOString().slice(0, 10) : null,
      rentFreeTo: l.rentFreeTo ? l.rentFreeTo.toISOString().slice(0, 10) : null,
      leaseTypeId: l.leaseTypeId,
      leaseType: terms.find((v) => v.id === l.leaseTypeId) ?? null,
      usageId: l.usageId,
      usage: terms.find((v) => v.id === l.usageId) ?? null,
      noticeDays: l.noticeDays,
      terminatedAt: l.terminatedAt,
      terminationReason: l.terminationReason,
      note: l.note,
      attachments,
      unitIds: l.units.map((u) => u.unitId),
      billingGroups: Object.fromEntries(l.units.filter((u) => u.billingGroup).map((u) => [u.unitId, u.billingGroup as string])),
      labels: l.labels.map((x) => x.label.name),
      chargeRules: l.chargeRules.map((r) => ({
        chargeTypeId: r.chargeTypeId,
        amount: r.amount.toString(),
        frequencyMonths: r.frequencyMonths,
        timing: r.timing,
        proration: r.proration,
        firstInvoiceOnly: r.firstInvoiceOnly,
        unitId: r.unitId,
        startDate: r.startDate ? r.startDate.toISOString().slice(0, 10) : null,
        endDate: r.endDate ? r.endDate.toISOString().slice(0, 10) : null,
        followsStandard: r.followsStandard,
      })),
    };
  }),

  /** Charges booked ahead for a future month on this lease. Pending ones are
   *  still editable; a billed one is history and only shows where it landed. */
  plannedCharges: withPermission('lease.read')
    .input(z.object({ leaseId: z.string() }))
    .query(async ({ ctx, input }) => {
      const rows = await ctx.prisma.plannedCharge.findMany({
        where: { leaseId: input.leaseId, organizationId: ctx.organizationId ?? undefined },
        orderBy: [{ period: 'asc' }, { createdAt: 'asc' }],
        include: { chargeType: { select: { nameEn: true, nameZh: true } }, unit: { select: { name: true } } },
      });
      const billed = rows.filter((r) => r.billedInvoiceId).map((r) => r.billedInvoiceId as string);
      const invoices = billed.length
        ? await ctx.prisma.invoice.findMany({ where: { id: { in: billed } }, select: { id: true, number: true, billingPeriod: true } })
        : [];
      const noteOf = new Map(invoices.map((i) => [i.id, i.number ?? i.billingPeriod]));
      return rows.map((r) => ({
        id: r.id,
        chargeTypeId: r.chargeTypeId,
        chargeTypeName: r.chargeType.nameZh ?? r.chargeType.nameEn,
        unitId: r.unitId,
        unitName: r.unit?.name ?? null,
        period: r.period,
        description: r.description,
        amount: r.amount.toFixed(2),
        billedOn: r.billedInvoiceId ? noteOf.get(r.billedInvoiceId) ?? null : null,
      }));
    }),

  addPlannedCharge: withPermission('lease.update')
    .input(
      z.object({
        leaseId: z.string(),
        chargeTypeId: z.string(),
        unitId: z.string().optional().nullable(),
        period: z.string().regex(/^\d{4}-\d{2}$/, 'Period must be YYYY-MM'),
        description: z.string().min(1),
        amount: z.string().regex(/^\d+(\.\d{1,2})?$/, 'Enter a valid amount'),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const lease = await ctx.prisma.lease.findFirst({
        where: { id: input.leaseId, organizationId: ctx.organizationId ?? undefined, deletedAt: null },
        select: { id: true, units: { select: { unitId: true } } },
      });
      if (!lease) throw new TRPCError({ code: 'NOT_FOUND', message: 'Lease not found' });
      if (input.unitId && !lease.units.some((u) => u.unitId === input.unitId)) {
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'Selected units are not on this lease' });
      }
      const row = await ctx.prisma.plannedCharge.create({
        data: {
          organizationId: ctx.organizationId ?? '',
          leaseId: input.leaseId,
          chargeTypeId: input.chargeTypeId,
          unitId: input.unitId || null,
          period: input.period,
          description: input.description,
          amount: input.amount,
          createdByUserId: ctx.user.id,
        },
      });
      return { id: row.id };
    }),

  /** Only while it is still pending — once billed it is on a debit note, and
   *  that note is what has to change. */
  removePlannedCharge: withPermission('lease.update')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const row = await ctx.prisma.plannedCharge.findFirst({
        where: { id: input.id, organizationId: ctx.organizationId ?? undefined },
        select: { id: true, billedInvoiceId: true },
      });
      if (!row) throw new TRPCError({ code: 'NOT_FOUND', message: 'Planned charge not found' });
      if (row.billedInvoiceId) throw new TRPCError({ code: 'BAD_REQUEST', message: 'This planned charge is already on a debit note; edit that note instead' });
      await ctx.prisma.plannedCharge.delete({ where: { id: input.id } });
      return { ok: true };
    }),

  /** Every label already in use, so the picker offers the shared vocabulary. */
  labels: withPermission('lease.read').query(({ ctx }) =>
    ctx.prisma.leaseLabel.findMany({
      where: { organizationId: ctx.organizationId ?? undefined },
      orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
      select: { id: true, name: true },
    }),
  ),

  create: withPermission('lease.create')
    .input(leaseInput)
    .mutation(async ({ ctx, input }) => {
      const orgId = ctx.organizationId ?? '';
      await checkLeaseTerms(ctx.prisma, orgId, input.leaseTypeId ?? null, input.usageId ?? null);
      checkFollowing(input.chargeRules);
      checkRentFree(input);
      return ctx.prisma.$transaction(async (tx) => {
        const propertyIds = await checkLeaseUnits(tx, orgId, input.unitIds);
        // The office's own number when it typed one; otherwise the sequence —
        // through the one place every document is numbered, so a lease follows
        // the format set on the Settings page, yearly restart included.
        const reference = await assignNumber(tx, orgId, 'LEASE', input.reference, { date: new Date(), propertyIds });
        const lease = await tx.lease.create({
          data: {
            organizationId: orgId,
            reference,
            tenantId: input.tenantId,
            status: input.status,
            currency: input.currency,
            startDate: new Date(input.startDate),
            endDate: new Date(input.endDate),
            dueDayOfMonth: input.dueDayOfMonth ?? null,
            bankAccountId: input.bankAccountId || null,
            depositMonths: input.depositMonths,
            // Never copied from `renewedFromId`: a rent-free period is part of
            // the original signing, so a renewal only has one if this call says
            // so. Nothing here reads the renewed-from lease's fields.
            rentFreeFrom: input.rentFreeFrom ? new Date(input.rentFreeFrom) : null,
            rentFreeTo: input.rentFreeTo ? new Date(input.rentFreeTo) : null,
            leaseTypeId: input.leaseTypeId || null,
            usageId: input.usageId || null,
            noticeDays: input.noticeDays ?? null,
            note: input.note ?? null,
            renewedFromId: input.renewedFromId || null,
            units: { create: input.unitIds.map((unitId) => ({ unitId, billingGroup: groupOf(input.billingGroups, unitId) })) },
            chargeRules: {
              create: input.chargeRules.map((r, i) => ({
                chargeTypeId: r.chargeTypeId,
                amount: r.amount,
                frequencyMonths: r.frequencyMonths,
                timing: r.timing,
                proration: r.proration,
                firstInvoiceOnly: r.firstInvoiceOnly,
                unitId: r.unitId ?? null,
                startDate: r.startDate ? new Date(r.startDate) : null,
                endDate: r.endDate ? new Date(r.endDate) : null,
                followsStandard: r.followsStandard,
                sortOrder: i,
              })),
            },
          },
        });
        // A renewal is saved ahead of time as a DRAFT with a future start; the
        // old lease keeps running until it ends. The monthly lifecycle transition
        // (billing.service.transitionLeases) later ends the old one and activates
        // this one — so nothing is ended here.
        await syncLabels(tx, ctx.organizationId ?? '', lease.id, input.labels);
        return { id: lease.id };
      });
    }),

  update: withPermission('lease.update')
    .input(leaseInput.extend({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const { id, unitIds, chargeRules } = input;
      await checkLeaseTerms(ctx.prisma, ctx.organizationId ?? undefined, input.leaseTypeId ?? null, input.usageId ?? null);
      checkFollowing(input.chargeRules);
      // Against the term as it is being saved, not the stored one: moving the
      // start date away from the window is the same mistake as typing the wrong
      // window, and only one of the two is visible on the form.
      checkRentFree(input);
      await ctx.prisma.$transaction(async (tx) => {
        // Gate the whole update on an org- and archive-scoped existence check, so a
        // caller can't edit another org's (or an archived) lease by guessing an id.
        const existing = await tx.lease.findFirst({
          where: { id, organizationId: ctx.organizationId ?? undefined, deletedAt: null },
          select: { id: true, currency: true, status: true, units: { select: { unitId: true } } },
        });
        if (!existing) throw new TRPCError({ code: 'NOT_FOUND' });
        await checkLeaseUnits(tx, ctx.organizationId ?? '', unitIds, existing.units.map((u) => u.unitId));
        // Ending a tenancy carries a date, a final debit note and a deposit to
        // settle — it is the Terminate action, not a field on the edit form.
        // Editing may move a lease between DRAFT and ACTIVE, or leave it as is.
        if (input.status !== existing.status && (input.status === 'TERMINATED' || input.status === 'ENDED')) {
          throw new TRPCError({ code: 'BAD_REQUEST', message: 'Use Terminate to end a lease; its status cannot be set by editing.' });
        }
        // A lease's documents inherit its currency; changing it once money has moved
        // would desync issued invoices/receipts/deposits from the ledger. Refuse.
        if (input.currency !== existing.currency) {
          const [invoices, depositCount, journal] = await Promise.all([
            tx.invoice.count({ where: { leaseId: id, status: { not: 'VOID' } } }),
            tx.deposit.count({ where: { leaseId: id } }),
            tx.journalLine.count({ where: { leaseId: id } }),
          ]);
          if (invoices > 0 || depositCount > 0 || journal > 0) {
            throw new TRPCError({ code: 'CONFLICT', message: "Cannot change a lease's currency once it has debit notes, deposits, or ledger activity." });
          }
        }
        await tx.lease.update({
          where: { id },
          data: {
            tenantId: input.tenantId,
            status: input.status,
            currency: input.currency,
            startDate: new Date(input.startDate),
            endDate: new Date(input.endDate),
            dueDayOfMonth: input.dueDayOfMonth ?? null,
            bankAccountId: input.bankAccountId || null,
            depositMonths: input.depositMonths,
            rentFreeFrom: input.rentFreeFrom ? new Date(input.rentFreeFrom) : null,
            rentFreeTo: input.rentFreeTo ? new Date(input.rentFreeTo) : null,
            leaseTypeId: input.leaseTypeId || null,
            usageId: input.usageId || null,
            noticeDays: input.noticeDays ?? null,
            note: input.note ?? null,
          },
        });
        // A note's payee is frozen only when it is issued; until then it pays
        // into whatever account its lease does now, so it never has to be
        // voided and raised again to pick up a change.
        await tx.invoice.updateMany({
          where: { leaseId: id, status: { in: PRE_ISSUE_STATUSES } },
          data: { bankAccountId: input.bankAccountId || null },
        });
        // Charge rules aren't referenced by issued invoices (amounts are copied to
        // lines), so replace-in-place is safe.
        await tx.chargeRule.deleteMany({ where: { leaseId: id } });
        await tx.chargeRule.createMany({
          data: chargeRules.map((r, i) => ({
            leaseId: id,
            chargeTypeId: r.chargeTypeId,
            amount: r.amount,
            frequencyMonths: r.frequencyMonths,
            timing: r.timing,
            proration: r.proration,
            firstInvoiceOnly: r.firstInvoiceOnly,
            unitId: r.unitId ?? null,
            startDate: r.startDate ? new Date(r.startDate) : null,
            endDate: r.endDate ? new Date(r.endDate) : null,
            followsStandard: r.followsStandard,
            sortOrder: i,
          })),
        });
        await tx.leaseUnit.deleteMany({ where: { leaseId: id } });
        if (unitIds.length) {
          await tx.leaseUnit.createMany({ data: unitIds.map((unitId) => ({ leaseId: id, unitId, billingGroup: groupOf(input.billingGroups, unitId) })) });
        }
        await syncLabels(tx, ctx.organizationId ?? '', id, input.labels);
      });
      return { id };
    }),

  /** What a termination would leave behind: open debit notes, held deposits and
   * any scheduled renewal. Warnings only — none of them block, because a move-out
   * normally has exactly these loose ends and the deposit settlement squares them. */
  terminationPreflight: withPermission('lease.read')
    .input(z.object({ id: z.string() }))
    .query(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? '';
      const lease = await ctx.prisma.lease.findFirst({
        where: { id: input.id, organizationId: org, deletedAt: null },
        select: { id: true, reference: true, status: true, currency: true, startDate: true, endDate: true },
      });
      if (!lease) throw new TRPCError({ code: 'NOT_FOUND' });

      const [openInvoices, heldDeposits, renewal] = await Promise.all([
        ctx.billing.leaseOpenInvoices(org, lease.id),
        ctx.deposits.heldForLease(org, lease.id),
        ctx.prisma.lease.findFirst({
          where: { organizationId: org, renewedFromId: lease.id, deletedAt: null, status: { in: ['DRAFT', 'ACTIVE'] } },
          select: { id: true, reference: true, startDate: true },
        }),
      ]);

      return {
        reference: lease.reference,
        status: lease.status,
        currency: lease.currency,
        startDate: lease.startDate,
        endDate: lease.endDate,
        openInvoices,
        heldDeposits,
        // A scheduled renewal still activates on its own start date — terminating
        // the parent does not cancel it, so say so rather than silently diverge.
        scheduledRenewal: renewal,
      };
    }),

  /** End a tenancy early: records the date and reason, then raises the final
   * part-month debit note. The only way a lease becomes TERMINATED. */
  terminate: withPermission('lease.update')
    .input(
      z.object({
        id: z.string(),
        terminationDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Pick a termination date'),
        reason: z.string().optional(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.billing.terminateLease({
        organizationId: ctx.organizationId ?? '',
        leaseId: input.id,
        terminationDate: new Date(`${input.terminationDate}T00:00:00.000Z`),
        reason: input.reason ?? null,
      }),
    ),

  /** Soft-delete (archive). Only a non-ACTIVE lease with no unsettled invoices can
   * be archived, so an archived lease never hides money still owed. Reversible. */
  archive: withPermission('lease.delete')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? undefined;
      const lease = await ctx.prisma.lease.findFirst({
        where: { id: input.id, organizationId: org, deletedAt: null },
        select: { status: true },
      });
      if (!lease) throw new TRPCError({ code: 'NOT_FOUND' });
      if (lease.status === 'ACTIVE') {
        throw new TRPCError({ code: 'CONFLICT', message: 'End or terminate the lease before archiving it.' });
      }
      const openInvoices = await ctx.prisma.invoice.count({
        where: { leaseId: input.id, status: { in: ['ISSUED', 'PARTIALLY_PAID'] } },
      });
      if (openInvoices > 0) {
        throw new TRPCError({ code: 'CONFLICT', message: `This lease still has ${openInvoices} unsettled debit note(s); handle them first.` });
      }
      const heldDeposits = await ctx.prisma.deposit.count({
        where: { leaseId: input.id, status: { in: ['HELD', 'PARTIALLY_APPLIED'] } },
      });
      if (heldDeposits > 0) {
        throw new TRPCError({ code: 'CONFLICT', message: `This lease still has ${heldDeposits} unsettled deposit(s); settle them first.` });
      }
      await ctx.prisma.lease.update({ where: { id: input.id }, data: { deletedAt: new Date() } });
      return { id: input.id };
    }),

  restore: withPermission('lease.delete')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      // Keep the "live lease ⇒ live parent" invariant symmetric with archive:
      // don't un-archive a lease back under an archived (hidden) property/tenant.
      const lease = await ctx.prisma.lease.findFirst({
        where: { id: input.id, organizationId: ctx.organizationId ?? undefined, deletedAt: { not: null } },
        select: { units: { select: { unit: { select: { property: { select: { id: true, deletedAt: true } } } } } }, tenant: { select: { deletedAt: true } } },
      });
      if (!lease) throw new TRPCError({ code: 'NOT_FOUND' });
      if (propertiesOf(lease.units).some((p) => p.deletedAt) || lease.tenant.deletedAt) {
        throw new TRPCError({ code: 'CONFLICT', message: 'Restore the archived property/tenant before restoring this lease.' });
      }
      await ctx.prisma.lease.update({ where: { id: input.id }, data: { deletedAt: null } });
      return { id: input.id };
    }),
});
