import type { Prisma } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { Decimal, sum } from '@rms/domain';
import { z } from 'zod';
import { STAFF_EVIDENCE } from '../../attachments/attachment.service';
import { invoiceArState } from '../../billing/invoice-ar';
import { ISSUED_STATUSES } from '../../billing/invoice-status';
import { addressOf, buildingOf, leaseBuilding, propertiesOf } from '../../common/lease-premises';
import { sumCents } from '../money-util';
import { router, tenantProcedure } from '../trpc';

/** Tenant-facing API. Every procedure scopes strictly to ctx.tenantId, so a
 * logged-in tenant can only ever see their own leases, invoices and deposits.
 * Drafts and anything still in approval are never exposed. */
export const portalRouter = router({
  summary: tenantProcedure.query(async ({ ctx }) => {
    const open = await ctx.prisma.invoice.findMany({
      where: { lease: { tenantId: ctx.tenantId }, status: { in: ['ISSUED', 'PARTIALLY_PAID'] } },
      include: { lines: { select: { amount: true } } },
    });
    // What is still OWED, read from the ledger — not the face value of the note.
    // Summing the lines tells a tenant who has already part-paid, or had a
    // deposit applied to their arrears, that they still owe the whole thing.
    const byCurrency = new Map<string, Decimal>();
    let openCount = 0;
    for (const i of open) {
      const { outstanding } = await invoiceArState(ctx.prisma as unknown as Prisma.TransactionClient, i.organizationId, i.id);
      if (outstanding.lte(0)) continue;
      openCount += 1;
      byCurrency.set(i.currency, (byCurrency.get(i.currency) ?? new Decimal(0)).plus(outstanding));
    }
    // Grouped by currency — never sum HKD and SGD into one figure.
    return {
      openInvoices: openCount,
      outstanding: [...byCurrency].map(([currency, amount]) => ({ currency, amount: amount.toFixed(2) })),
    };
  }),

  invoices: tenantProcedure.query(async ({ ctx }) => {
    const invoices = await ctx.prisma.invoice.findMany({
      where: { lease: { tenantId: ctx.tenantId }, status: { in: ISSUED_STATUSES } },
      orderBy: [{ createdAt: 'desc' }],
      include: { lease: { select: { reference: true } }, lines: { select: { amount: true } } },
    });
    // The ledger position per note, so the list can show what is left to pay
    // rather than only what was originally charged.
    const outstandingById = new Map<string, string>();
    for (const i of invoices) {
      const { outstanding } = await invoiceArState(ctx.prisma as unknown as Prisma.TransactionClient, i.organizationId, i.id);
      outstandingById.set(i.id, outstanding.toFixed(2));
    }
    return invoices.map((i) => ({
      id: i.id,
      number: i.number,
      status: i.status,
      currency: i.currency,
      billingPeriod: i.billingPeriod,
      dueDate: i.dueDate,
      leaseRef: i.lease.reference,
      total: sumCents(i.lines),
      outstanding: outstandingById.get(i.id) ?? sumCents(i.lines),
    }));
  }),

  invoice: tenantProcedure.input(z.object({ id: z.string() })).query(async ({ ctx, input }) => {
    const inv = await ctx.prisma.invoice.findFirst({
      where: { id: input.id, lease: { tenantId: ctx.tenantId }, status: { in: ISSUED_STATUSES } },
      include: {
        lines: { orderBy: { sortOrder: 'asc' } },
        lease: { select: { reference: true, ...leaseBuilding } },
      },
    });
    if (!inv) throw new TRPCError({ code: 'NOT_FOUND', message: 'Debit note not found' });

    // The tenant's own payment submissions against this note, so a refusal is
    // visible where they made it rather than only in an email. `note` is the
    // office's internal remark and is deliberately not among these fields.
    // Receipts only — what the tenant submitted. A deposit receipt drawn onto the
    // note is the office's booking of money already paid, not a submission.
    const receipts = await ctx.prisma.receipt.findMany({
      where: { tenantId: ctx.tenantId, kind: 'RECEIPT', allocations: { some: { items: { some: { invoiceId: inv.id } } } } },
      orderBy: { createdAt: 'desc' },
      select: { id: true, number: true, status: true, amount: true, receivedDate: true, rejectionReason: true, overpayments: { select: { amount: true } } },
    });
    const receiptAtts = receipts.length
      ? await ctx.prisma.attachment.findMany({
          // The tenant's own proof only. What the office attached when refusing
          // a payment is tagged STAFF_EVIDENCE and is not theirs to see — the
          // reason is; the bank statement behind it is not.
          // `NOT: { role: X }` would drop the tenant's own proof as well: in SQL
          // `NOT (role = 'X')` is NULL for a NULL role, so an untagged row is
          // excluded rather than kept. Spell out that null is wanted.
          where: {
            ownerType: 'RECEIPT',
            ownerId: { in: receipts.map((r) => r.id) },
            OR: [{ role: null }, { role: { not: STAFF_EVIDENCE } }],
          },
          orderBy: { createdAt: 'asc' },
          select: { id: true, ownerId: true, filename: true, mimeType: true },
        })
      : [];

    // What the note charged, and what is left on it. The payment form must use
    // the second: submitReceipt refuses anything above the ledger outstanding,
    // so prefilling the face value makes every payment on a part-paid note fail.
    const { outstanding } = await invoiceArState(ctx.prisma as unknown as Prisma.TransactionClient, inv.organizationId, inv.id);

    return {
      id: inv.id,
      number: inv.number,
      status: inv.status,
      currency: inv.currency,
      billingPeriod: inv.billingPeriod,
      dueDate: inv.dueDate,
      issueDate: inv.issueDate,
      leaseRef: inv.lease.reference,
      propertyName: buildingOf(propertiesOf(inv.lease.units)),
      total: sumCents(inv.lines),
      outstanding: outstanding.toFixed(2),
      lines: inv.lines.map((l) => ({
        id: l.id,
        kind: l.kind,
        description: l.description,
        amount: l.amount.toString(),
      })),
      receipts: receipts.map((r) => ({
        id: r.id,
        number: r.number,
        status: r.status,
        // What the tenant paid, and of it what the note did not owe — held for
        // the lease as advance payment, moving with this receipt.
        amount: sum([r.amount.toString(), ...r.overpayments.map((o) => o.amount.toString())]).toFixed(2),
        excess: r.overpayments.length ? sum(r.overpayments.map((o) => o.amount.toString())).toFixed(2) : null,
        receivedDate: r.receivedDate,
        rejectionReason: r.rejectionReason,
        attachments: receiptAtts.filter((a) => a.ownerId === r.id).map((a) => ({ id: a.id, filename: a.filename, mimeType: a.mimeType })),
      })),
    };
  }),

  /** The meters in the units this tenant rents, with what was last read, so the
   *  form can show where the dial stood when someone last looked at it. A meter
   *  inside a tenant's flat cannot be read by the office without access, which
   *  is why the tenant is asked at all. */
  myMeters: tenantProcedure.query(async ({ ctx }) => {
    const meters = await ctx.prisma.meter.findMany({
      where: { isActive: true, units: { some: { unit: { leaseUnits: { some: { lease: { tenantId: ctx.tenantId, status: 'ACTIVE', deletedAt: null } } } } } } },
      select: {
        id: true,
        serialNo: true,
        chargeType: { select: { nameEn: true, nameZh: true } },
        units: { select: { unit: { select: { name: true } } } },
      },
    });
    if (meters.length === 0) return [];
    // Only a confirmed reading is a starting point — a declaration still waiting
    // to be checked is not yet a fact about the dial.
    const last = await ctx.prisma.meterReading.findMany({
      where: { meterId: { in: meters.map((m) => m.id) }, status: 'CONFIRMED' },
      orderBy: [{ periodEnd: 'desc' }],
      select: { meterId: true, readingEnd: true, periodEnd: true },
    });
    const lastOf = new Map<string, { readingEnd: string; periodEnd: Date }>();
    for (const r of last) {
      if (!lastOf.has(r.meterId)) lastOf.set(r.meterId, { readingEnd: r.readingEnd.toString(), periodEnd: r.periodEnd });
    }
    const pending = await ctx.prisma.meterReading.findMany({
      where: { meterId: { in: meters.map((m) => m.id) }, status: { in: ['PENDING', 'REJECTED'] }, submittedByUserId: ctx.user.id },
      orderBy: { createdAt: 'desc' },
      select: { id: true, meterId: true, status: true, readingEnd: true, periodEnd: true, rejectionReason: true },
    });
    return meters.map((m) => ({
      id: m.id,
      serialNo: m.serialNo,
      utility: m.chargeType.nameZh ?? m.chargeType.nameEn,
      units: m.units.map((u) => u.unit.name).join(', '),
      last: lastOf.get(m.id) ?? null,
      mine: pending
        .filter((r) => r.meterId === m.id)
        .map((r) => ({ id: r.id, status: r.status, readingEnd: r.readingEnd.toString(), periodEnd: r.periodEnd, rejectionReason: r.rejectionReason })),
    }));
  }),

  /** A tenant reads their own dial and declares it. It is priced but not
   *  billable until the office confirms it against the photo — the number comes
   *  from the party being charged for it. */
  submitMeterReading: tenantProcedure
    .input(
      z.object({
        meterId: z.string(),
        readingEnd: z.string().regex(/^\d+(\.\d{1,3})?$/, 'Enter the number on the dial'),
        readOn: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Pick the date you read it'),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const meter = await ctx.prisma.meter.findFirst({
        where: {
          id: input.meterId,
          isActive: true,
          units: { some: { unit: { leaseUnits: { some: { lease: { tenantId: ctx.tenantId, status: 'ACTIVE', deletedAt: null } } } } } },
        },
        select: { id: true },
      });
      if (!meter) throw new TRPCError({ code: 'NOT_FOUND', message: 'Meter not found' });

      const last = await ctx.prisma.meterReading.findFirst({
        where: { meterId: meter.id, status: 'CONFIRMED' },
        orderBy: [{ periodEnd: 'desc' }],
        select: { readingEnd: true, periodEnd: true },
      });
      const periodEnd = new Date(input.readOn);
      const periodStart = last ? last.periodEnd : periodEnd;
      const readingStart = last ? last.readingEnd.toString() : input.readingEnd;
      if (periodEnd < periodStart) {
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'That date is before the last reading' });
      }
      if (Number(input.readingEnd) < Number(readingStart)) {
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'The dial cannot have gone backwards; check the number' });
      }
      // Deliberately unpriced: grossAmount is set when the office confirms it,
      // from the tariff in force then, and an unpriced reading cannot be billed
      // even if the status gate were ever bypassed.
      const row = await ctx.prisma.meterReading.create({
        data: {
          meterId: meter.id,
          readingStart,
          readingEnd: input.readingEnd,
          periodStart,
          periodEnd,
          status: 'PENDING',
          submittedByUserId: ctx.user.id,
        },
      });
      return { id: row.id };
    }),

  leases: tenantProcedure.query(async ({ ctx }) => {
    const rows = await ctx.prisma.lease.findMany({
      // Not DRAFT. A renewal is stored as a future-dated draft months ahead —
      // the header above promises drafts are never exposed, and a tenant seeing
      // next year's terms before anyone has agreed them is what that promise is
      // for. It becomes visible when the transition makes it ACTIVE.
      where: { tenantId: ctx.tenantId, deletedAt: null, status: { not: 'DRAFT' } },
      orderBy: { startDate: 'desc' },
      select: {
        id: true,
        reference: true,
        status: true,
        startDate: true,
        endDate: true,
        units: { select: { unit: { select: { property: { select: { id: true, name: true, address: true } } } } } },
      },
    });
    return rows.map(({ units, ...l }) => {
      const properties = propertiesOf(units);
      return { ...l, property: { name: buildingOf(properties), address: addressOf(properties) } };
    });
  }),

  /** The tenant's own deposits. Settled/refunded ones carry a printable statement. */
  /** Money paid ahead of a lease's debit notes — deposit receipts. Only an
   *  approved one is the tenant's to keep a receipt for; one that bounced
   *  stays listed, as its receipt is stamped. */
  advanceReceipts: tenantProcedure.query(async ({ ctx }) => {
    const rows = await ctx.prisma.receipt.findMany({
      // An overpaid part is on its payment's receipt, under that debit note.
      where: { tenantId: ctx.tenantId, kind: 'DEPOSIT_RECEIPT', status: { in: ['APPROVED', 'BOUNCED'] }, sourceReceiptId: null },
      orderBy: [{ receivedDate: 'desc' }, { number: 'desc' }],
      select: { id: true, number: true, status: true, amount: true, currency: true, receivedDate: true, lease: { select: { reference: true } } },
    });
    return rows.map((r) => ({
      id: r.id,
      number: r.number,
      status: r.status,
      amount: r.amount.toFixed(2),
      currency: r.currency,
      receivedDate: r.receivedDate,
      leaseRef: r.lease?.reference ?? null,
    }));
  }),

  deposits: tenantProcedure.query(async ({ ctx }) => {
    const rows = await ctx.prisma.deposit.findMany({
      where: { tenantId: ctx.tenantId },
      orderBy: [{ createdAt: 'desc' }],
      include: { lease: { select: { reference: true } } },
    });
    return rows.map((d) => ({
      id: d.id,
      number: d.number,
      status: d.status,
      currency: d.currency,
      amount: d.amount.toString(),
      leaseRef: d.lease?.reference ?? null,
      hasStatement: d.status === 'SETTLED' || d.status === 'REFUNDED',
    }));
  }),

  /** The monthly statements the office has sent the tenant, newest period
   *  first; each opens as the PDF that was sent (/api/documents/statement/:id.pdf). */
  statements: tenantProcedure.query(({ ctx }) => ctx.statements.forTenant(ctx.tenantId)),

  /** The itemised settlement statement for one of the tenant's own deposits. */
  depositStatement: tenantProcedure.input(z.object({ depositId: z.string() })).query(async ({ ctx, input }) => {
    const deposit = await ctx.prisma.deposit.findFirst({
      where: { id: input.depositId, tenantId: ctx.tenantId },
      select: { organizationId: true },
    });
    if (!deposit) throw new TRPCError({ code: 'NOT_FOUND', message: 'Deposit not found' });
    const statement = await ctx.deposits.getSettlement(deposit.organizationId, input.depositId);
    if (!statement) throw new TRPCError({ code: 'NOT_FOUND', message: 'No settlement statement' });
    return statement;
  }),

  settlementMethods: tenantProcedure.query(({ ctx }) =>
    ctx.prisma.settlementMethod.findMany({
      where: { isActive: true },
      orderBy: { sortOrder: 'asc' },
      select: { id: true, nameEn: true, nameZh: true, requiresReference: true },
    }),
  ),

  submitReceipt: tenantProcedure
    .input(
      z.object({
        invoiceId: z.string(),
        amount: z.string().regex(/^\d+(\.\d{1,2})?$/, 'Enter a valid amount'),
        settlementMethodId: z.string().optional(),
        reference: z.string().optional(),
      }),
    )
    .mutation(({ ctx, input }) =>
      ctx.payments.submitReceipt({
        organizationId: ctx.organizationId ?? '',
        tenantId: ctx.tenantId,
        invoiceId: input.invoiceId,
        amount: input.amount,
        settlementMethodId: input.settlementMethodId ?? null,
        reference: input.reference ?? null,
        uploadedByUserId: ctx.user.id,
      }),
    ),

  // ── Maintenance (tenant-facing) ─────────────────────────────
  /** The tenant's own leases → property + pickable units, plus the configured
   * priority options, for the report form. */
  reportOptions: tenantProcedure.query(async ({ ctx }) => {
    const [leases, priorities] = await Promise.all([
      ctx.prisma.lease.findMany({
        where: { tenantId: ctx.tenantId, deletedAt: null, status: 'ACTIVE' },
        orderBy: { startDate: 'desc' },
        select: {
          id: true,
          reference: true,
          units: { select: { unit: { select: { id: true, name: true, property: { select: { id: true, name: true } } } } } },
        },
      }),
      ctx.prisma.referenceValue.findMany({
        where: { organizationId: ctx.organizationId ?? undefined, domain: 'MAINTENANCE_PRIORITY', isActive: true },
        orderBy: { sortOrder: 'asc' },
        select: { id: true, nameEn: true, nameZh: true },
      }),
    ]);
    return {
      leases: leases.map((l) => ({
        leaseId: l.id,
        reference: l.reference,
        propertyName: buildingOf(propertiesOf(l.units)),
        units: l.units.map((u) => ({ id: u.unit.id, name: u.unit.name })),
      })),
      priorities,
    };
  }),

  myMaintenanceRequests: tenantProcedure.query(async ({ ctx }) => {
    const rows = await ctx.prisma.maintenanceRequest.findMany({
      where: { tenantId: ctx.tenantId },
      orderBy: { createdAt: 'desc' },
      include: { property: { select: { name: true } }, unit: { select: { name: true } } },
    });
    return rows.map((r) => ({
      id: r.id,
      title: r.title,
      description: r.description,
      status: r.status,
      propertyName: r.property.name,
      unitName: r.unit?.name ?? null,
      createdAt: r.createdAt,
    }));
  }),

  reportMaintenance: tenantProcedure
    .input(
      z.object({
        leaseId: z.string(),
        unitId: z.string().optional(),
        priorityId: z.string().optional(),
        title: z.string().min(3).max(120),
        description: z.string().max(2000).optional(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      // Re-scope through the tenant's OWN lease: org/property come from the DB
      // row, never the client (mirrors submitReceipt's server-side trust).
      const lease = await ctx.prisma.lease.findFirst({
        where: { id: input.leaseId, tenantId: ctx.tenantId, deletedAt: null },
        select: { organizationId: true, units: { select: { unitId: true, unit: { select: { propertyId: true } } } } },
      });
      if (!lease) throw new TRPCError({ code: 'NOT_FOUND', message: 'Lease not found' });
      const unit = input.unitId ? lease.units.find((u) => u.unitId === input.unitId) : lease.units[0];
      if (!unit) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Unit is not on this lease' });
      return ctx.maintenance.create({
        organizationId: lease.organizationId,
        // The purchase the unit is on — the reported one, else the lease's first.
        propertyId: unit.unit.propertyId,
        unitId: input.unitId ?? null,
        tenantId: ctx.tenantId,
        leaseId: input.leaseId,
        priorityId: input.priorityId ?? null,
        title: input.title,
        description: input.description ?? null,
        reportedByUserId: ctx.user.id,
      });
    }),
});
