import { z } from 'zod';
import { buildingOf, leaseBuilding, propertiesOf } from '../../common/lease-premises';
import { leaseCredit, remainingOf } from '../../payments/lease-credit';
import { router, withPermission } from '../trpc';

const money = z.string().regex(/^\d+(\.\d{1,2})?$/);

/**
 * Deposit Receipts — the office's name for money a tenant paid for a lease
 * before its debit note existed, or over what a note owed. Each is a receipt
 * of kind DEPOSIT_RECEIPT; approving, refusing and bouncing one go through the
 * receipts router like any receipt. What is here is what is particular to
 * them: the list with what each has paid and has left, and recording one
 * against a lease. Under the receipt permissions — it is a receipt.
 */
export const depositReceiptsRouter = router({
  list: withPermission('receipt.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.receipt.findMany({
      where: { organizationId: ctx.organizationId ?? undefined, kind: 'DEPOSIT_RECEIPT' },
      orderBy: [{ createdAt: 'desc' }],
      include: {
        settlementMethod: { select: { nameEn: true } },
        lease: { select: { reference: true, ...leaseBuilding } },
        sourceReceipt: { select: { number: true } },
        allocations: { include: { items: { include: { invoice: { select: { number: true } } } } } },
      },
    });
    const tenants = await ctx.prisma.tenant.findMany({ where: { id: { in: [...new Set(rows.map((r) => r.tenantId))] } }, select: { id: true, name: true } });
    const nameOf = new Map(tenants.map((t) => [t.id, t.name]));
    const atts = await ctx.prisma.attachment.findMany({
      where: { organizationId: ctx.organizationId ?? undefined, ownerType: 'RECEIPT', ownerId: { in: rows.map((r) => r.id) } },
      orderBy: { createdAt: 'asc' },
      select: { id: true, ownerId: true, filename: true, mimeType: true },
    });
    return rows.map((r) => ({
      id: r.id,
      number: r.number,
      status: r.status,
      currency: r.currency,
      amount: r.amount.toFixed(2),
      /** Still to be drawn onto the lease's notes. Only an approved one holds
       *  anything; a pending one has not been banked yet. */
      remaining: r.status === 'APPROVED' ? remainingOf(r).toFixed(2) : '0.00',
      receivedDate: r.receivedDate,
      reference: r.reference,
      note: r.note,
      method: r.settlementMethod?.nameEn ?? null,
      tenantName: nameOf.get(r.tenantId) ?? '—',
      leaseReference: r.lease?.reference ?? null,
      propertyName: r.lease ? buildingOf(propertiesOf(r.lease.units)) : null,
      /** Set when this is the overpaid part of a receipt — it moves with that one. */
      sourceReceiptNumber: r.sourceReceipt?.number ?? null,
      applications: r.allocations.flatMap((a) =>
        a.items.map((i) => ({ invoiceNumber: i.invoice.number, amount: i.amount.toFixed(2), withdrawn: a.status === 'VOID' })),
      ),
      attachments: atts.filter((a) => a.ownerId === r.id).map(({ ownerId: _o, ...a }) => a),
    }));
  }),

  /** Tenants with a lease a deposit receipt can be for: current or still to start. */
  tenants: withPermission('receipt.read').query(({ ctx }) =>
    ctx.prisma.tenant.findMany({
      where: {
        organizationId: ctx.organizationId ?? undefined,
        deletedAt: null,
        leases: { some: { deletedAt: null, status: { in: ['ACTIVE', 'DRAFT'] } } },
      },
      orderBy: { name: 'asc' },
      select: { id: true, name: true, nameZh: true },
    }),
  ),

  /** One tenant's leases a deposit receipt can be for, with what each already holds. */
  leases: withPermission('receipt.read')
    .input(z.object({ tenantId: z.string() }))
    .query(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const leases = await ctx.prisma.lease.findMany({
        where: { organizationId, tenantId: input.tenantId, deletedAt: null, status: { in: ['ACTIVE', 'DRAFT'] } },
        orderBy: [{ startDate: 'asc' }],
        select: { id: true, reference: true, currency: true, status: true, ...leaseBuilding },
      });
      return Promise.all(
        leases.map(async (l) => ({
          id: l.id,
          reference: l.reference,
          currency: l.currency,
          status: l.status,
          propertyName: buildingOf(propertiesOf(l.units)),
          credit: (await leaseCredit(ctx.prisma, organizationId, l.id)).toFixed(2),
        })),
      );
    }),

  create: withPermission('receipt.create')
    .input(
      z.object({
        tenantId: z.string(),
        leaseId: z.string(),
        amount: money,
        settlementMethodId: z.string().optional(),
        reference: z.string().optional(),
        receivedDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Pick a date').optional(),
        note: z.string().optional(),
        /** The deposit receipt number, when the office types its own. */
        number: z.string().optional(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.payments.recordDepositReceipt({
        organizationId: ctx.organizationId ?? '',
        tenantId: input.tenantId,
        leaseId: input.leaseId,
        amount: input.amount,
        settlementMethodId: input.settlementMethodId ?? null,
        reference: input.reference ?? null,
        // UTC midnight, as every calendar date here is stored.
        receivedDate: input.receivedDate ? new Date(input.receivedDate) : undefined,
        note: input.note ?? null,
        uploadedByUserId: ctx.user.id,
        number: input.number,
      }),
    ),
});
