import type { Prisma } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { invoiceArState } from '../../billing/invoice-ar';
import { letterheadFor, letterheadPropertySelect } from '../../common/letterhead';
import { buildingOf, propertiesOf } from '../../common/lease-premises';
import { unitsLabel } from '../../common/unit-label';
import { leaseCredit } from '../../payments/lease-credit';
import { sumCents } from '../money-util';
import { router, withPermission } from '../trpc';

const periodSchema = z
  .string()
  .regex(/^\d{4}-\d{2}$/, 'Period must be YYYY-MM');

/** The units each split note bills, as one label ("617–622"), by invoice id.
 *  A note for the whole lease has none. */
async function scopeLabels(
  prisma: Pick<Prisma.TransactionClient, 'unit'>,
  invoices: readonly { id: string; unitScope: Prisma.JsonValue }[],
): Promise<Map<string, string>> {
  const scoped = invoices.filter((i) => Array.isArray(i.unitScope));
  if (scoped.length === 0) return new Map();
  const ids = [...new Set(scoped.flatMap((i) => i.unitScope as string[]))];
  const names = new Map((await prisma.unit.findMany({ where: { id: { in: ids } }, select: { id: true, name: true } })).map((u) => [u.id, u.name]));
  return new Map(scoped.map((i) => [i.id, unitsLabel((i.unitScope as string[]).map((id) => names.get(id) ?? '?'))]));
}

export const invoicesRouter = router({
  list: withPermission('invoice.read').query(async ({ ctx }) => {
    const invoices = await ctx.prisma.invoice.findMany({
      where: { organizationId: ctx.organizationId ?? undefined },
      orderBy: [{ createdAt: 'desc' }],
      include: {
        lease: { select: { reference: true, tenant: { select: { name: true } } } },
        lines: { select: { amount: true } },
      },
    });
    const scopeOf = await scopeLabels(ctx.prisma, invoices);
    return invoices.map((inv) => ({
      id: inv.id,
      number: inv.number,
      status: inv.status,
      currency: inv.currency,
      billingPeriod: inv.billingPeriod,
      dueDate: inv.dueDate,
      issueDate: inv.issueDate,
      scheduledIssueDate: inv.scheduledIssueDate,
      leaseRef: inv.lease.reference,
      /** The units a split note bills, e.g. "617–622"; null for the whole lease. */
      units: scopeOf.get(inv.id) ?? null,
      tenantName: inv.lease.tenant.name,
      lineCount: inv.lines.length,
      total: sumCents(inv.lines),
    }));
  }),

  get: withPermission('invoice.read').input(z.object({ id: z.string() })).query(async ({ ctx, input }) => {
    const invoice = await ctx.prisma.invoice.findFirst({
      where: { id: input.id, organizationId: ctx.organizationId ?? undefined },
      include: {
        lines: { orderBy: { sortOrder: 'asc' }, include: { chargeType: { select: { code: true } } } },
        lease: {
          select: {
            reference: true,
            tenantId: true,
            tenant: { select: { name: true, nameZh: true } },
            // For the letterhead readout below — the same select the renderer
            // resolves the printed heading from, off each unit's property.
            units: {
              select: {
                unit: {
                  select: {
                    property: { select: letterheadPropertySelect },
                  },
                },
              },
            },
          },
        },
      },
    });
    if (!invoice) throw new TRPCError({ code: 'NOT_FOUND', message: 'Debit note not found' });
    // What is still owed is derived from the ledger, never stored — the same
    // read the payment path validates against, so the form cannot offer an
    // amount the server will refuse.
    const { outstanding } = await invoiceArState(ctx.prisma as unknown as Prisma.TransactionClient, ctx.organizationId ?? '', invoice.id);
    // What the lease holds from deposit receipts — paid onto this note when it
    // is issued, so a draft can say so before it goes out.
    const credit = await leaseCredit(ctx.prisma as unknown as Prisma.TransactionClient, ctx.organizationId ?? '', invoice.leaseId);
    // Evidence hangs off individual charges (no FK relation) — one query, grouped.
    const files = await ctx.prisma.attachment.findMany({
      where: { organizationId: ctx.organizationId ?? undefined, ownerType: 'INVOICE_LINE', ownerId: { in: invoice.lines.map((l) => l.id) } },
      orderBy: { createdAt: 'asc' },
      select: { id: true, ownerId: true, filename: true, mimeType: true },
    });
    const filesByLine = new Map<string, { id: string; filename: string; mimeType: string }[]>();
    for (const f of files) {
      const list = filesByLine.get(f.ownerId) ?? [];
      list.push({ id: f.id, filename: f.filename, mimeType: f.mimeType });
      filesByLine.set(f.ownerId, list);
    }
    // Whose name this note prints under. Resolved through the same helper the
    // PDF uses, so the readout cannot disagree with the paper: `frozen` says it
    // came off the note itself (captured at issue and never moving again)
    // rather than off the building's current setting. A note issued before
    // snapshots existed has none and is pinned to the organisation just the
    // same — `letterheadFor` treats it as immutable, so `frozen` must too, or
    // the screen would offer to print a heading that note can never carry.
    const org = await ctx.prisma.organization.findFirstOrThrow({ where: { id: ctx.organizationId ?? undefined } });
    const letterhead = letterheadFor({
      org,
      properties: propertiesOf(invoice.lease.units),
      snapshot: invoice.letterheadSnapshot,
      issued: invoice.number !== null,
    });
    // Return a flat DTO (Decimals → strings) so the client's inferred type stays shallow.
    return {
      id: invoice.id,
      number: invoice.number,
      letterhead: { name: letterhead.name, address: letterhead.address, frozen: invoice.letterheadSnapshot != null || invoice.number !== null },
      status: invoice.status,
      currency: invoice.currency,
      billingPeriod: invoice.billingPeriod,
      dueDate: invoice.dueDate,
      issueDate: invoice.issueDate,
      scheduledIssueDate: invoice.scheduledIssueDate,
      leaseId: invoice.leaseId,
      leaseRef: invoice.lease.reference,
      units: (await scopeLabels(ctx.prisma, [invoice])).get(invoice.id) ?? null,
      leaseCredit: credit.toFixed(2),
      tenantId: invoice.lease.tenantId,
      tenantName: invoice.lease.tenant.name,
      total: sumCents(invoice.lines),
      outstanding: outstanding.toFixed(2),
      lines: invoice.lines.map((l) => {
        const meta = (l.meta ?? null) as Record<string, unknown> | null;
        // A metered charge splits into one line per unit; the reading it came
        // from is what makes those lines one thing to a reader.
        const meter =
          meta && typeof meta === 'object' && typeof meta.meterReadingId === 'string'
            ? {
                readingId: meta.meterReadingId,
                serialNo: typeof meta.serialNo === 'string' ? meta.serialNo : null,
                unitName: String(meta.unitName ?? ''),
                readingStart: String(meta.readingStart ?? ''),
                readingEnd: String(meta.readingEnd ?? ''),
                unitCount: Number(meta.unitCount ?? 1),
                deductionNote: typeof meta.deductionNote === 'string' ? meta.deductionNote : null,
              }
            : null;
        return {
          id: l.id,
          kind: l.kind,
          description: l.description,
          amount: l.amount.toFixed(2),
          periodStart: l.periodStart,
          periodEnd: l.periodEnd,
          chargeTypeCode: l.chargeType?.code ?? null,
          isAdjustment: Boolean(meta && typeof meta === 'object' && (meta as { adjustment?: boolean }).adjustment),
          meter,
          attachments: filesByLine.get(l.id) ?? [],
        };
      }),
    };
  }),

  /** Payment records allocated to this invoice — receipt no., date, method, status, amount. */
  payments: withPermission('invoice.read')
    .input(z.object({ invoiceId: z.string() }))
    .query(async ({ ctx, input }) => {
      const items = await ctx.prisma.receiptAllocationItem.findMany({
        where: { invoiceId: input.invoiceId, allocation: { receipt: { organizationId: ctx.organizationId ?? undefined } } },
        include: { allocation: { include: { receipt: { include: { settlementMethod: { select: { nameEn: true } } } } } } },
      });
      // Proof files hang off the receipt (polymorphic, no FK) — one query,
      // grouped. Downloading re-authorises per receipt, so a user who could not
      // fetch them is not offered them either.
      const canSeeProof = ctx.user.permissions.includes('receipt.read');
      const atts = canSeeProof
        ? await ctx.prisma.attachment.findMany({
            where: {
              organizationId: ctx.organizationId ?? undefined,
              ownerType: 'RECEIPT',
              ownerId: { in: [...new Set(items.map((it) => it.allocation.receipt.id))] },
            },
            orderBy: { createdAt: 'asc' },
            select: { id: true, ownerId: true, filename: true, mimeType: true },
          })
        : [];
      const attByReceipt = new Map<string, { id: string; filename: string; mimeType: string }[]>();
      for (const a of atts) {
        const arr = attByReceipt.get(a.ownerId) ?? [];
        arr.push({ id: a.id, filename: a.filename, mimeType: a.mimeType });
        attByReceipt.set(a.ownerId, arr);
      }
      return items
        .map((it) => ({
          receiptId: it.allocation.receipt.id,
          receiptNumber: it.allocation.receipt.number,
          /** DEPOSIT_RECEIPT: a drawing of the lease's credit, withdrawable on its own. */
          kind: it.allocation.receipt.kind,
          allocationId: it.allocation.id,
          status: it.allocation.receipt.status,
          allocationStatus: it.allocation.status,
          receivedDate: it.allocation.receipt.receivedDate,
          note: it.allocation.receipt.note,
          method: it.allocation.receipt.settlementMethod?.nameEn ?? null,
          currency: it.allocation.receipt.currency,
          amount: it.amount.toString(),
          attachments: attByReceipt.get(it.allocation.receipt.id) ?? [],
        }))
        .sort((a, b) => a.receivedDate.getTime() - b.receivedDate.getTime());
    }),

  /** Takes a deposit receipt's drawing back off this note — the way to void a
   *  note paid from credit. The credit returns to the lease. */
  withdrawCredit: withPermission('receipt.update')
    .input(z.object({ allocationId: z.string() }))
    .mutation(({ ctx, input }) =>
      ctx.payments.withdrawCredit({ organizationId: ctx.organizationId ?? '', allocationId: input.allocationId, userId: ctx.user.id }),
    ),

  billableLeases: withPermission('invoice.read').query(async ({ ctx }) => {
    const leases = await ctx.prisma.lease.findMany({
      where: { organizationId: ctx.organizationId ?? undefined, status: 'ACTIVE', deletedAt: null },
      orderBy: { reference: 'asc' },
      select: {
        id: true,
        reference: true,
        tenant: { select: { name: true } },
        units: { select: { billingGroup: true, unit: { select: { id: true, name: true, property: { select: { id: true, name: true } } } } } },
      },
    });
    return leases.map((l) => ({
      id: l.id,
      reference: l.reference,
      tenant: l.tenant,
      property: { name: buildingOf(propertiesOf(l.units)) },
      units: l.units.map((u) => ({ id: u.unit.id, name: u.unit.name, billingGroup: u.billingGroup })),
    }));
  }),

  generateDraft: withPermission('invoice.create')
    .input(z.object({ leaseId: z.string(), period: periodSchema, unitIds: z.array(z.string()).optional() }))
    .mutation(({ ctx, input }) =>
      ctx.billing.generateDraft({
        organizationId: ctx.organizationId ?? '',
        leaseId: input.leaseId,
        period: input.period,
        unitIds: input.unitIds,
      }),
    ),

  /** A lease's notes for a period by its billing groups, the missing ones only. */
  generateGroupDrafts: withPermission('invoice.create')
    .input(z.object({ leaseId: z.string(), period: periodSchema }))
    .mutation(({ ctx, input }) => ctx.billing.generateGroupDrafts({ organizationId: ctx.organizationId ?? '', leaseId: input.leaseId, period: input.period })),

  /** Carry an invoice's outstanding balance onto the lease's next (draft) DN. */
  carryForward: withPermission('invoice.create')
    .input(z.object({ invoiceId: z.string(), targetPeriod: periodSchema.optional() }))
    .mutation(({ ctx, input }) =>
      ctx.billing.carryForward({
        organizationId: ctx.organizationId ?? '',
        invoiceId: input.invoiceId,
        targetPeriod: input.targetPeriod,
        carriedByUserId: ctx.user.id,
      }),
    ),

  issue: withPermission('invoice.approve')
    .input(z.object({ invoiceId: z.string(), number: z.string().optional() }))
    .mutation(({ ctx, input }) =>
      ctx.billing.issue({ organizationId: ctx.organizationId ?? '', invoiceId: input.invoiceId, issuedByUserId: ctx.user.id, number: input.number }),
    ),

  /** Defer this debit note's issue to a chosen date; null cancels. Gated on
   *  invoice.approve rather than invoice.update — a schedule is an issue, just
   *  later, and produces the same number, posting and tenant notice. */
  schedule: withPermission('invoice.approve')
    .input(z.object({ invoiceId: z.string(), date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Pick a date').nullable() }))
    .mutation(({ ctx, input }) =>
      ctx.billing.setSchedule({
        organizationId: ctx.organizationId ?? '',
        invoiceId: input.invoiceId,
        // UTC midnight, as every other calendar date in this system is stored.
        date: input.date ? new Date(input.date) : null,
      }),
    ),

  /** Whether this debit note needs approval, where its live round stands, and
   *  every round's signature trail. */
  approval: withPermission('invoice.read')
    .input(z.object({ invoiceId: z.string() }))
    .query(({ ctx, input }) =>
      ctx.billing.approvalState({
        organizationId: ctx.organizationId ?? '',
        invoiceId: input.invoiceId,
        userId: ctx.user.id,
      }),
    ),

  /** Send a DRAFT into its approval workflow (DRAFT → PENDING_APPROVAL). */
  submitForApproval: withPermission('invoice.update')
    .input(z.object({ invoiceId: z.string() }))
    .mutation(({ ctx, input }) =>
      ctx.billing.submitForApproval({ organizationId: ctx.organizationId ?? '', invoiceId: input.invoiceId }),
    ),

  /** Void an invoice — the append-only alternative to deletion. A DRAFT is just
   * marked VOID; a clean, fully-unpaid ISSUED invoice is reversed in the ledger. */
  voidInvoice: withPermission('invoice.delete')
    .input(z.object({ invoiceId: z.string() }))
    .mutation(({ ctx, input }) =>
      ctx.billing.voidInvoice({ organizationId: ctx.organizationId ?? '', invoiceId: input.invoiceId }),
    ),

  /** Rebuild an unissued note's rule-derived charges from the lease as it stands
   *  now — after a rate change, a late meter reading or a lease correction. */
  regenerate: withPermission('invoice.update')
    .input(z.object({ invoiceId: z.string() }))
    .mutation(({ ctx, input }) =>
      ctx.billing.regenerateDraft({ organizationId: ctx.organizationId ?? '', invoiceId: input.invoiceId }),
    ),

  /** Add a manual adjustment line (waiver/credit or one-off charge) to a DRAFT. */
  addAdjustment: withPermission('invoice.update')
    .input(
      z.object({
        invoiceId: z.string(),
        chargeTypeId: z.string(),
        description: z.string().min(1),
        amount: z.string().regex(/^\d+(\.\d{1,2})?$/),
        credit: z.boolean(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.billing.addAdjustment({ organizationId: ctx.organizationId ?? '', ...input }),
    ),

  /** Waive accrued late interest on a DRAFT (removes its INTEREST lines). */
  waiveInterest: withPermission('invoice.update')
    .input(z.object({ invoiceId: z.string() }))
    .mutation(({ ctx, input }) =>
      ctx.billing.waiveInterest({ organizationId: ctx.organizationId ?? '', invoiceId: input.invoiceId }),
    ),

  /** Remove any line from an unissued note — a draft is a working document. */
  /** Put a carried-forward balance back on the note it came from. Not
   *  invoice.create like carryForward: this edits a draft rather than raising
   *  one, and the same key already governs every other change to its lines. */
  unwindCarryForward: withPermission('invoice.update')
    .input(z.object({ lineId: z.string() }))
    .mutation(async ({ ctx, input }) => {
      await ctx.billing.unwindCarryForward({
        organizationId: ctx.organizationId ?? '',
        lineId: input.lineId,
        reversedByUserId: ctx.user.id,
      });
      return { ok: true };
    }),

  removeLine: withPermission('invoice.update')
    .input(z.object({ lineId: z.string() }))
    .mutation(({ ctx, input }) =>
      ctx.billing.removeLine({ organizationId: ctx.organizationId ?? '', lineId: input.lineId }),
    ),

  /** Manual trigger of the monthly billing run (same code the scheduler calls). */
  runDrafts: withPermission('invoice.create')
    .input(z.object({ period: periodSchema }))
    .mutation(async ({ ctx, input }) => {
      const orgId = ctx.organizationId ?? '';
      // Transition leases first (end finished, activate due renewals, carry deposits),
      // the same as the monthly scheduler, so a manual run stays consistent.
      await ctx.billing.transitionLeases({ organizationId: orgId, asOf: new Date() });
      return ctx.billing.generateDraftsForPeriod({ organizationId: orgId, period: input.period });
    }),
});
