import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { awaitingReview } from '../../payments/awaiting-review';
import { router, withPermission } from '../trpc';

export const receiptsRouter = router({
  list: withPermission('receipt.read').query(async ({ ctx }) => {
    // Receipts only: deposit receipts are listed on their own page.
    const receipts = await ctx.prisma.receipt.findMany({
      where: { organizationId: ctx.organizationId ?? undefined, kind: 'RECEIPT' },
      orderBy: [{ createdAt: 'desc' }],
      include: {
        settlementMethod: { select: { nameEn: true } },
        overpayments: { select: { number: true, amount: true } },
        allocations: {
          include: { items: { include: { invoice: { select: { number: true, billingPeriod: true } } } } },
        },
      },
    });
    // Receipt has no tenant relation (only tenantId) — resolve names in one query.
    const tenantIds = [...new Set(receipts.map((r) => r.tenantId))];
    const tenants = await ctx.prisma.tenant.findMany({
      where: { id: { in: tenantIds } },
      select: { id: true, name: true },
    });
    const nameOf = new Map(tenants.map((t) => [t.id, t.name]));

    // Polymorphic attachments (no FK relation) — one query, grouped by receipt.
    const atts = await ctx.prisma.attachment.findMany({
      where: { organizationId: ctx.organizationId ?? undefined, ownerType: 'RECEIPT', ownerId: { in: receipts.map((r) => r.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 receipts.map((r) => ({
      id: r.id,
      number: r.number,
      status: r.status,
      currency: r.currency,
      amount: r.amount.toString(),
      receivedDate: r.receivedDate,
      reference: r.reference,
      tenantName: nameOf.get(r.tenantId) ?? '—',
      method: r.settlementMethod?.nameEn ?? null,
      invoices: r.allocations
        .flatMap((a) => a.items.map((i) => i.invoice?.number ?? i.invoice?.billingPeriod))
        .filter((v): v is string => Boolean(v)),
      /** The overpaid part of the same payment, booked as a deposit receipt. */
      overpaid: r.overpayments.map((o) => ({ number: o.number, amount: o.amount.toString() })),
      attachments: attByReceipt.get(r.id) ?? [],
    }));
  }),

  /** Payments waiting on the office, oldest first — the payments half of My
   *  Approvals. A receipt has no approval workflow: whoever may approve one on
   *  the Receipts page sees it here. */
  pending: withPermission('receipt.update').query(async ({ ctx }) => {
    const rows = await ctx.prisma.receipt.findMany({
      where: awaitingReview(ctx.organizationId ?? undefined),
      orderBy: { createdAt: 'asc' },
      include: {
        lease: { select: { reference: true } },
        overpayments: { select: { number: true, amount: true } },
        allocations: { include: { items: { include: { invoice: { select: { number: true, billingPeriod: true } } } } } },
      },
    });
    const uploaderIds = rows.flatMap((r) => (r.uploadedByUserId ? [r.uploadedByUserId] : []));
    const [tenants, tenantLogins] = await Promise.all([
      ctx.prisma.tenant.findMany({ where: { id: { in: [...new Set(rows.map((r) => r.tenantId))] } }, select: { id: true, name: true } }),
      // Sent from the portal = uploaded by a login that belongs to a tenant.
      ctx.prisma.user.findMany({ where: { id: { in: uploaderIds }, tenantId: { not: null } }, select: { id: true } }),
    ]);
    const nameOf = new Map(tenants.map((t) => [t.id, t.name]));
    const fromPortal = new Set(tenantLogins.map((u) => u.id));
    return rows.map((r) => ({
      id: r.id,
      number: r.number,
      kind: r.kind,
      currency: r.currency,
      amount: r.amount.toString(),
      createdAt: r.createdAt,
      tenantName: nameOf.get(r.tenantId) ?? '—',
      fromTenant: r.uploadedByUserId !== null && fromPortal.has(r.uploadedByUserId),
      invoices: r.allocations
        .flatMap((a) => a.items.map((i) => i.invoice?.number ?? i.invoice?.billingPeriod))
        .filter((v): v is string => Boolean(v)),
      leaseReference: r.lease?.reference ?? null,
      overpaid: r.overpayments.map((o) => ({ number: o.number, amount: o.amount.toString() })),
    }));
  }),

  /** Full detail of one receipt — allocated invoices, method, date, note, attachments. */
  get: withPermission('receipt.read')
    .input(z.object({ id: z.string() }))
    .query(async ({ ctx, input }) => {
      const r = await ctx.prisma.receipt.findFirst({
        where: { id: input.id, organizationId: ctx.organizationId ?? undefined },
        include: {
          settlementMethod: { select: { nameEn: true } },
          allocations: { include: { items: { include: { invoice: { select: { id: true, number: true, billingPeriod: true } } } } } },
        },
      });
      if (!r) throw new TRPCError({ code: 'NOT_FOUND' });
      const tenant = await ctx.prisma.tenant.findFirst({ where: { id: r.tenantId }, select: { name: true } });
      const attachments = await ctx.prisma.attachment.findMany({
        where: { organizationId: ctx.organizationId ?? undefined, ownerType: 'RECEIPT', ownerId: r.id },
        orderBy: { createdAt: 'asc' },
        select: { id: true, filename: true, mimeType: true },
      });
      return {
        id: r.id,
        number: r.number,
        status: r.status,
        currency: r.currency,
        amount: r.amount.toString(),
        receivedDate: r.receivedDate,
        reference: r.reference,
        note: r.note,
        method: r.settlementMethod?.nameEn ?? null,
        tenantName: tenant?.name ?? '—',
        allocations: r.allocations.flatMap((a) =>
          a.items.map((i) => ({ invoiceNumber: i.invoice?.number ?? i.invoice?.billingPeriod ?? '—', amount: i.amount.toString() })),
        ),
        attachments,
      };
    }),

  /** Tenants who currently owe something, for the bulk-payment picker. */
  payableTenants: withPermission('receipt.read').query(async ({ ctx }) => {
    const tenants = await ctx.prisma.tenant.findMany({
      where: {
        organizationId: ctx.organizationId ?? undefined,
        deletedAt: null,
        leases: { some: { invoices: { some: { status: { in: ['ISSUED', 'PARTIALLY_PAID'] } } } } },
      },
      orderBy: { name: 'asc' },
      select: { id: true, name: true, nameZh: true },
    });
    return tenants;
  }),

  /** A tenant's still-owed invoices with live outstanding, for allocating a payment. */
  openInvoices: withPermission('receipt.read')
    .input(z.object({ tenantId: z.string() }))
    .query(({ ctx, input }) => ctx.payments.listOpenInvoices(ctx.organizationId ?? '', input.tenantId)),

  approve: withPermission('receipt.update')
    .input(z.object({ receiptId: z.string() }))
    .mutation(({ ctx, input }) =>
      ctx.payments.approve({
        organizationId: ctx.organizationId ?? '',
        receiptId: input.receiptId,
        reviewedByUserId: ctx.user.id,
      }),
    ),

  reject: withPermission('receipt.update')
    .input(z.object({ receiptId: z.string(), reason: z.string().optional() }))
    .mutation(({ ctx, input }) =>
      ctx.payments.reject({
        organizationId: ctx.organizationId ?? '',
        receiptId: input.receiptId,
        reason: input.reason ?? null,
        reviewedByUserId: ctx.user.id,
      }),
    ),

  /** A dishonoured (bounced) payment — reverses the ledger, re-opens invoices.
   *  No longer offered in the back office: rejection covers a payment that was
   *  never posted, and this is the separate case of one that was. Kept because a
   *  cheque really can bounce and nothing else can unwind a posted receipt. */
  bounce: withPermission('receipt.update')
    .input(z.object({ receiptId: z.string(), reason: z.string().optional() }))
    .mutation(({ ctx, input }) =>
      ctx.payments.bounce({
        organizationId: ctx.organizationId ?? '',
        receiptId: input.receiptId,
        reason: input.reason ?? null,
        reviewedByUserId: ctx.user.id,
      }),
    ),

  /** Admin records one payment settling several of a tenant's invoices at once. */
  recordBulk: withPermission('receipt.create')
    .input(
      z.object({
        tenantId: z.string(),
        amount: z.string().regex(/^\d+(\.\d{1,2})?$/),
        settlementMethodId: z.string().optional(),
        reference: z.string().optional(),
        // What the office actually saw on the statement, and why. The receipt
        // has carried both columns since the schema was written; the amount had
        // to be dated "now" only because nothing passed them through.
        receivedDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Pick a date').optional(),
        note: z.string().optional(),
        allocations: z
          .array(z.object({ invoiceId: z.string(), amount: z.string().regex(/^\d+(\.\d{1,2})?$/) }))
          .min(1),
        /** The receipt number, when the office types its own. */
        number: z.string().optional(),
        /** Paid over what the notes owe: held for one of the tenant's leases as a
         *  deposit receipt of its own. */
        overpayment: z.object({ amount: z.string().regex(/^\d+(\.\d{1,2})?$/), leaseId: z.string() }).optional(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.payments.recordBulkPayment({
        number: input.number,
        overpayment: input.overpayment ?? null,
        organizationId: ctx.organizationId ?? '',
        tenantId: input.tenantId,
        amount: input.amount,
        settlementMethodId: input.settlementMethodId ?? null,
        reference: input.reference ?? null,
        // UTC midnight, as every other calendar date in this system is stored —
        // the admin renders dates in UTC, so an offset here would show a day early.
        receivedDate: input.receivedDate ? new Date(input.receivedDate) : undefined,
        note: input.note ?? null,
        uploadedByUserId: ctx.user.id,
        allocations: input.allocations,
      }),
    ),
});
