import { createHash } from 'node:crypto';
import { invoiceKindWord, isDormitoryTenant } from '../../lib/invoice-words';
import { FeeBearer, InvoiceStatus, PaymentRequestStatus, PaymentStatus, Prisma, Role, type PaymentRequest } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow, runWithTenantContext } from '../../lib/tenantContext';
import { env, publicWebUrl } from '../../config/env';
import { BadRequestError, ConflictError, NotFoundError, ServiceUnavailableError } from '../../lib/errors';
import { sendEmail } from '../../lib/email';
import { currentBrand } from '../../lib/email-brand';
import { sendWhatsApp, sendWhatsAppTemplate } from '../../lib/whatsapp';
import { paymentLinkEmail } from '../../lib/email-templates';
import * as rzp from '../../lib/razorpay';
import { invoiceNumber } from '../billing/invoice-pdf.service';
import { failPayment } from '../billing/billing.service';
import * as notify from '../notifications/notifications.service';
import { applyAccountEvent, onlineCollectionFor } from './payment-account.service';
import { applyVirtualAccountCredit } from './collections.service';

/**
 * Online collection: a student pays an invoice through a hosted Razorpay
 * Payment Link, and the money lands in HostelCare's books exactly once.
 *
 * Three rules keep this honest:
 *   1. A PaymentRequest row is written BEFORE Razorpay is asked for a link,
 *      so every link traces back to an invoice, a student and an amount.
 *   2. Only the webhook records money. The redirect page and the polling
 *      clients read state; they never write it.
 *   3. Every webhook is claimed by a unique insert first, and the request
 *      row is locked while it is processed — so a replay, a retry or two
 *      events racing can never produce two payments.
 */

const MIN_LINK_SECONDS = 16 * 60; // Razorpay refuses expire_by under 15 minutes

// ── Fees ───────────────────────────────────────────────────────────────────

export interface FeeBreakdown {
  baseAmount: number;
  gatewayFee: number;
  gatewayFeeTax: number;
  routeFee: number;
  routeFeeTax: number;
  totalFee: number;
  /** What the payer is charged. */
  grossAmount: number;
  /** What the hostel receives after fees. */
  netAmount: number;
  feeBearer: FeeBearer;
}

/**
 * Gateway fee + GST on it, and the Route fee + GST on it, in whole rupees.
 * STUDENT bears them: gross = base + fees, hostel receives base.
 * HOSTEL bears them: gross = base, hostel receives base − fees.
 */
export function feeBreakdown(baseAmount: number, feeBearer: FeeBearer): FeeBreakdown {
  const pct = (n: number, p: number) => Math.round((n * p) / 100);
  const gatewayFee = pct(baseAmount, env.RAZORPAY_GATEWAY_FEE_PERCENT);
  const gatewayFeeTax = pct(gatewayFee, env.RAZORPAY_GATEWAY_FEE_TAX_PERCENT);
  const routeFee = env.RAZORPAY_ROUTE_REQUIRED ? pct(baseAmount, env.RAZORPAY_ROUTE_FEE_PERCENT) : 0;
  const routeFeeTax = pct(routeFee, env.RAZORPAY_ROUTE_FEE_TAX_PERCENT);
  const totalFee = gatewayFee + gatewayFeeTax + routeFee + routeFeeTax;
  const student = feeBearer === FeeBearer.STUDENT;
  return {
    baseAmount,
    gatewayFee,
    gatewayFeeTax,
    routeFee,
    routeFeeTax,
    totalFee,
    grossAmount: student ? baseAmount + totalFee : baseAmount,
    netAmount: student ? baseAmount : Math.max(0, baseAmount - totalFee),
    feeBearer,
  };
}

// ── Public shape ───────────────────────────────────────────────────────────

/** A pending link past its time reads as EXPIRED even before Razorpay says so. */
export function effectiveStatus(r: Pick<PaymentRequest, 'status' | 'expiresAt'>, now = new Date()): PaymentRequestStatus {
  if (r.status === PaymentRequestStatus.PENDING && r.expiresAt.getTime() <= now.getTime()) return PaymentRequestStatus.EXPIRED;
  return r.status;
}

export function publicRequest(r: PaymentRequest) {
  return {
    id: r.id,
    invoiceId: r.invoiceId,
    studentProfileId: r.studentProfileId,
    origin: r.origin,
    status: effectiveStatus(r),
    baseAmount: r.baseAmount,
    grossAmount: r.grossAmount,
    fees: { gatewayFee: r.gatewayFee, gatewayFeeTax: r.gatewayFeeTax, routeFee: r.routeFee, routeFeeTax: r.routeFeeTax, total: r.gatewayFee + r.gatewayFeeTax + r.routeFee + r.routeFeeTax },
    feeBearer: r.feeBearer,
    linkUrl: r.linkUrl,
    expiresAt: r.expiresAt,
    paidAt: r.paidAt,
    paymentId: r.paymentId,
    latestError: r.latestError,
    sentCount: r.sentCount,
    sentAt: r.sentAt,
    createdAt: r.createdAt,
  };
}
export type PublicPaymentRequest = ReturnType<typeof publicRequest>;

// ── Creating a link ────────────────────────────────────────────────────────

export interface CreateOptions {
  origin: 'STUDENT' | 'OFFICE' | 'REMINDER';
  createdById?: string;
  /** When the student asks: the invoice must be theirs, or it does not exist. */
  studentUserId?: string;
}

/**
 * Create a link for what is still owed on an invoice, or hand back the live
 * one. A pending link for a different balance (a part-payment landed since)
 * is cancelled and replaced, so the link always asks for exactly the balance.
 */
export async function createOrReuseRequest(invoiceId: string, opts: CreateOptions): Promise<PublicPaymentRequest> {
  const tenantId = getTenantIdOrThrow();
  const invoice = await db.invoice.findFirst({
    where: { id: invoiceId },
    include: {
      payments: { where: { status: PaymentStatus.CLEARED }, select: { amount: true } },
      student: { include: { user: { select: { id: true, name: true, email: true, phone: true } } } },
    },
  });
  if (!invoice || (opts.studentUserId && invoice.student.userId !== opts.studentUserId)) throw new NotFoundError('Invoice not found');
  const balance = invoice.amount - invoice.payments.reduce((n, p) => n + p.amount, 0);
  if (invoice.status === InvoiceStatus.PAID || balance <= 0) throw new ConflictError('This invoice is already settled', 'INVOICE_SETTLED');

  const collection = await onlineCollectionFor(tenantId);
  if (!collection.enabled) {
    if (collection.reason === 'GATEWAY_NOT_CONFIGURED') throw new ServiceUnavailableError('Online payments are not available on this server yet', collection.reason);
    throw new BadRequestError(
      collection.reason === 'ONLINE_COLLECTION_OFF' ? 'This hostel has not switched online payments on' : 'The hostel’s bank account is not yet active for online payments',
      collection.reason!,
    );
  }
  const settings = await db.tenantSettings.findFirst({ select: { feeBearer: true, billingFirmName: true } });
  const feeBearer = settings?.feeBearer ?? FeeBearer.STUDENT;

  // Reuse a live link for the same balance; replace one for a stale balance.
  const now = new Date();
  const live = await db.paymentRequest.findFirst({
    where: { invoiceId, status: PaymentRequestStatus.PENDING, expiresAt: { gt: new Date(now.getTime() + 60_000) } },
    orderBy: { createdAt: 'desc' },
  });
  if (live) {
    if (live.baseAmount === balance && live.feeBearer === feeBearer) return publicRequest(live);
    await cancelAtGateway(live);
    await db.paymentRequest.update({ where: { id: live.id }, data: { status: PaymentRequestStatus.CANCELLED, latestError: 'Replaced: the balance changed' } });
  }

  const fees = feeBreakdown(balance, feeBearer);
  const ttlSeconds = Math.max(MIN_LINK_SECONDS, env.PAYMENT_LINK_TTL_MINUTES * 60);
  const expiresAt = new Date(now.getTime() + ttlSeconds * 1000);
  const row = await db.paymentRequest.create({
    data: {
      tenantId,
      invoiceId,
      studentProfileId: invoice.studentProfileId,
      createdById: opts.origin === 'OFFICE' ? opts.createdById : opts.origin === 'REMINDER' ? 'REMINDER' : null,
      origin: opts.origin,
      baseAmount: fees.baseAmount,
      gatewayFee: fees.gatewayFee,
      gatewayFeeTax: fees.gatewayFeeTax,
      routeFee: fees.routeFee,
      routeFeeTax: fees.routeFeeTax,
      grossAmount: fees.grossAmount,
      amountPaise: fees.grossAmount * 100,
      feeBearer,
      expiresAt,
    },
  });

  const firm = settings?.billingFirmName?.trim() || 'HostelCare';
  const number = invoiceNumber(invoice.id, invoice.periodMonth);
  try {
    const link = await rzp.createPaymentLink({
      amountPaise: row.amountPaise,
      referenceId: row.id,
      description: `${firm} · ${number} · ${(await isDormitoryTenant(tenantId)) ? 'Bill' : invoice.type === 'RENT' ? 'Hostel rent' : invoice.type === 'MESS' ? 'Mess' : 'Charges'} ${invoice.periodMonth}`,
      customer: { name: invoice.student.user.name, email: invoice.student.user.email, contact: invoice.student.user.phone },
      // Ids only — Razorpay copies these onto the payment, and the webhook
      // uses them to find the row. No personal data lives in the notes.
      notes: { paymentRequestId: row.id, invoiceId: invoice.id, studentProfileId: invoice.studentProfileId, tenantId },
      callbackUrl: `${publicWebUrl}/pay/result`,
      expireBy: Math.floor(expiresAt.getTime() / 1000),
      transfer: collection.account?.razorpayAccountId
        ? { account: collection.account.razorpayAccountId, amountPaise: fees.netAmount * 100, notes: { tenantId, invoiceId: invoice.id } }
        : null,
    });
    const saved = await db.paymentRequest.update({ where: { id: row.id }, data: { linkId: link.id, linkUrl: link.short_url } });
    return publicRequest(saved);
  } catch (err) {
    // A link that was never issued leaves no trace: the row only ever
    // describes a link that exists.
    await db.paymentRequest.delete({ where: { id: row.id } }).catch(() => {});
    if (err instanceof rzp.RazorpayError) throw new ServiceUnavailableError(`The payment gateway refused to issue a link: ${err.message}`, 'GATEWAY_ERROR');
    throw err;
  }
}

async function cancelAtGateway(r: PaymentRequest): Promise<void> {
  if (!r.linkId) return;
  try {
    await rzp.cancelPaymentLink(r.linkId);
  } catch {
    // Already paid, expired or gone — the webhook will say which. Not fatal.
  }
}

// ── Reading, cancelling, sending ───────────────────────────────────────────

export async function getRequest(id: string, opts: { studentUserId?: string } = {}): Promise<PublicPaymentRequest> {
  const row = await db.paymentRequest.findFirst({ where: { id }, include: { student: { select: { userId: true } } } });
  if (!row || (opts.studentUserId && row.student.userId !== opts.studentUserId)) throw new NotFoundError('Payment request not found');
  return publicRequest(row);
}

export async function cancelRequest(id: string): Promise<PublicPaymentRequest> {
  const row = await db.paymentRequest.findFirst({ where: { id } });
  if (!row) throw new NotFoundError('Payment request not found');
  if (row.status !== PaymentRequestStatus.PENDING) throw new ConflictError(`This link is already ${row.status.toLowerCase()}`);
  await cancelAtGateway(row);
  return publicRequest(await db.paymentRequest.update({ where: { id }, data: { status: PaymentRequestStatus.CANCELLED } }));
}

/** Email (and WhatsApp, when configured) the link to the student. */
export async function sendRequest(id: string): Promise<PublicPaymentRequest & { emailed: boolean; messaged: boolean }> {
  const row = await db.paymentRequest.findFirst({
    where: { id },
    include: { invoice: true, student: { include: { user: { select: { id: true, name: true, email: true, phone: true } } } } },
  });
  if (!row) throw new NotFoundError('Payment request not found');
  if (effectiveStatus(row) !== PaymentRequestStatus.PENDING || !row.linkUrl) throw new ConflictError('Only a live link can be sent');
  const brand = await currentBrand();
  const firm = brand.firm;
  const user = row.student.user;
  let emailed = false;
  let messaged = false;
  if (user.email) {
    const mail = paymentLinkEmail({
      firm,
      brand,
      studentName: user.name,
      invoiceNumber: invoiceNumber(row.invoice.id, row.invoice.periodMonth),
      kind: invoiceKindWord(row.invoice.type, await isDormitoryTenant(row.tenantId)),
      periodLabel: notify.periodLabel(row.invoice.periodMonth, row.invoice.cycleMonths),
      baseAmount: row.baseAmount,
      grossAmount: row.grossAmount,
      feeBearer: row.feeBearer,
      dueDate: row.invoice.dueDate ? row.invoice.dueDate.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', timeZone: 'UTC' }) : null,
      linkUrl: row.linkUrl,
      expiresAt: row.expiresAt,
    });
    const r = await sendEmail(user.email, mail.subject, mail.text, mail.html);
    emailed = r.sent || r.mode === 'log';
  }
  if (user.phone) {
    const text = `Hi ${user.name}, pay ₹${row.grossAmount} for ${invoiceNumber(row.invoice.id, row.invoice.periodMonth)} (${row.invoice.periodMonth}) securely here: ${row.linkUrl} — ${firm}`;
    const r = env.WHATSAPP_TEMPLATE_PAYMENT_LINK
      ? await sendWhatsAppTemplate(user.phone, env.WHATSAPP_TEMPLATE_PAYMENT_LINK, [user.name, `₹${row.grossAmount}`, `${invoiceNumber(row.invoice.id, row.invoice.periodMonth)} · ${row.invoice.periodMonth}`, row.linkUrl], text, { tenantId: row.tenantId, userId: user.id, purpose: 'PAYMENT_LINK' })
      : await sendWhatsApp(user.phone, text, { tenantId: row.tenantId, userId: user.id, purpose: 'PAYMENT_LINK' });
    messaged = r.sent || r.mode === 'log';
  }
  const saved = await db.paymentRequest.update({ where: { id }, data: { sentCount: { increment: 1 }, sentAt: new Date() } });
  return { ...publicRequest(saved), emailed, messaged };
}

/**
 * The live link on each invoice, for decorating lists. One query for the
 * whole page; invoices without a live link map to nothing.
 */
export async function liveLinksFor(invoiceIds: string[]): Promise<Map<string, PublicPaymentRequest>> {
  const out = new Map<string, PublicPaymentRequest>();
  if (invoiceIds.length === 0) return out;
  const rows = await db.paymentRequest.findMany({
    where: { invoiceId: { in: invoiceIds }, status: { in: [PaymentRequestStatus.PENDING, PaymentRequestStatus.PAID] } },
    orderBy: { createdAt: 'desc' },
  });
  for (const r of rows) {
    if (out.has(r.invoiceId)) continue;
    const eff = effectiveStatus(r);
    if (eff === PaymentRequestStatus.PENDING || eff === PaymentRequestStatus.PAID) out.set(r.invoiceId, publicRequest(r));
  }
  return out;
}

// ── Webhook ────────────────────────────────────────────────────────────────

export interface RzpEntity {
  id?: string;
  amount?: number;
  status?: string;
  order_id?: string;
  method?: string;
  created_at?: number;
  reference_id?: string;
  notes?: Record<string, string> | string[];
  error_description?: string | null;
  error_code?: string | null;
  payment_id?: string;
  activation_status?: string;
  account_id?: string;
}
interface RzpWebhook {
  id?: string;
  event?: string;
  created_at?: number;
  account_id?: string;
  payload?: Record<string, { entity?: RzpEntity } | undefined>;
}

export type WebhookOutcome = { ok: true; result: string; eventId: string } | { ok: false; status: number; error: string };

/**
 * Verify, claim, process, acknowledge. Any throw after the claim releases
 * the claim and surfaces as a 500, so Razorpay retries; an event we cannot
 * use is acknowledged with 200 so it is never retried.
 */
export async function handleRazorpayWebhook(rawBody: Buffer, signature: string | undefined): Promise<WebhookOutcome> {
  if (!rzp.isWebhookConfigured()) return { ok: false, status: 503, error: 'Webhook secret not configured' };
  if (!rzp.verifyWebhookSignature(rawBody, signature)) return { ok: false, status: 400, error: 'Invalid webhook signature' };
  let body: RzpWebhook;
  try {
    body = JSON.parse(rawBody.toString('utf8')) as RzpWebhook;
  } catch {
    return { ok: false, status: 400, error: 'Body is not JSON' };
  }
  const eventType = body.event ?? 'unknown';
  const eventId = body.id ?? `digest_${createHash('sha256').update(rawBody).digest('hex').slice(0, 32)}`;

  // Claim first. A duplicate delivery stops here.
  let claimId: string;
  try {
    const claim = await prismaUnscoped.webhookEvent.create({ data: { provider: 'razorpay', eventId, eventType }, select: { id: true } });
    claimId = claim.id;
  } catch (e) {
    if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') return { ok: true, result: 'duplicate', eventId };
    throw e;
  }

  try {
    const result = await processEvent(eventType, body);
    await prismaUnscoped.webhookEvent.update({ where: { id: claimId }, data: { processedAt: new Date() } });
    return { ok: true, result, eventId };
  } catch (err) {
    await prismaUnscoped.webhookEvent.delete({ where: { id: claimId } }).catch(() => {});
    throw err;
  }
}

function notesOf(e: RzpEntity | undefined): Record<string, string> {
  const n = e?.notes;
  return n && !Array.isArray(n) ? n : {};
}

/** Find the request an event is about, by our id in the notes, the link's reference_id, or the link id. */
async function requestFor(body: RzpWebhook): Promise<PaymentRequest | null> {
  const link = body.payload?.payment_link?.entity;
  const payment = body.payload?.payment?.entity;
  const order = body.payload?.order?.entity;
  const candidates = [notesOf(payment).paymentRequestId, notesOf(link).paymentRequestId, notesOf(order).paymentRequestId, link?.reference_id].filter(Boolean) as string[];
  for (const id of candidates) {
    const row = await prismaUnscoped.paymentRequest.findUnique({ where: { id } });
    if (row) return row;
  }
  if (link?.id) return prismaUnscoped.paymentRequest.findUnique({ where: { linkId: link.id } });
  return null;
}

async function processEvent(eventType: string, body: RzpWebhook): Promise<string> {
  switch (eventType) {
    case 'payment_link.paid':
    case 'payment.captured':
    case 'order.paid': {
      const row = await requestFor(body);
      if (!row) return 'ignored:no_request';
      const payment = body.payload?.payment?.entity;
      if (!payment?.id) return 'ignored:no_payment';
      return markPaid(row, payment, body.payload?.payment_link?.entity ?? null);
    }
    case 'payment.failed': {
      const row = await requestFor(body);
      if (!row) return 'ignored:no_request';
      // A failed attempt does not close the link: the student can try again
      // on the same page. And it never touches a request already PAID.
      if (row.status !== PaymentRequestStatus.PENDING) return `ignored:${row.status.toLowerCase()}`;
      const payment = body.payload?.payment?.entity;
      await prismaUnscoped.paymentRequest.update({
        where: { id: row.id },
        data: { latestError: (payment?.error_description || payment?.error_code || 'Payment failed').slice(0, 300) },
      });
      return 'noted:failed_attempt';
    }
    case 'payment_link.expired':
    case 'payment_link.cancelled': {
      const row = await requestFor(body);
      if (!row) return 'ignored:no_request';
      if (row.status !== PaymentRequestStatus.PENDING) return `ignored:${row.status.toLowerCase()}`;
      const status = eventType === 'payment_link.expired' ? PaymentRequestStatus.EXPIRED : PaymentRequestStatus.CANCELLED;
      await prismaUnscoped.paymentRequest.update({ where: { id: row.id }, data: { status } });
      return `closed:${status.toLowerCase()}`;
    }
    case 'refund.processed': {
      const refund = body.payload?.refund?.entity;
      if (!refund?.payment_id) return 'ignored:no_payment';
      return reverseForRefund(refund.payment_id, refund.amount ?? null, refund.id ?? null);
    }
    case 'refund.created':
    case 'refund.failed': {
      // Created: note the id (an office-requested refund already has it).
      // Failed: the money stayed with the hostel, so the payment stays
      // cleared — only the refund attempt is marked, for the office to retry.
      const refund = body.payload?.refund?.entity;
      if (!refund?.payment_id) return 'ignored:no_payment';
      const payment = await prismaUnscoped.payment.findUnique({ where: { gatewayPaymentId: refund.payment_id } });
      if (!payment) return 'ignored:unknown_payment';
      if (payment.status === PaymentStatus.FAILED) return 'ignored:already_reversed';
      await prismaUnscoped.payment.update({
        where: { id: payment.id },
        data: eventType === 'refund.failed' ? { refundId: refund.id ?? payment.refundId, refundStatus: 'FAILED' } : { refundId: refund.id ?? payment.refundId, refundStatus: payment.refundStatus ?? 'REQUESTED', refundAmount: payment.refundAmount ?? (refund.amount != null ? Math.round(refund.amount / 100) : null) },
      });
      return eventType === 'refund.failed' ? 'noted:refund_failed' : 'noted:refund_created';
    }
    case 'virtual_account.credited': {
      const va = body.payload?.virtual_account?.entity;
      const payment = body.payload?.payment?.entity;
      if (!va?.id || !payment?.id) return 'ignored:no_virtual_account';
      return applyVirtualAccountCredit(va.id, payment as Parameters<typeof applyVirtualAccountCredit>[1]);
    }
    case 'account.activated':
    case 'account.needs_clarification':
    case 'account.updated':
    case 'account.suspended': {
      const acc = body.payload?.account?.entity;
      if (!acc?.id) return 'ignored:no_account';
      return (await applyAccountEvent(acc.id, 'account', acc.status)) ? 'account:updated' : 'ignored:unknown_account';
    }
    case 'product.route.under_review':
    case 'product.route.needs_clarification':
    case 'product.route.activated':
    case 'product.route.rejected': {
      const product = body.payload?.product?.entity;
      const accountId = product?.account_id ?? body.account_id;
      if (!accountId) return 'ignored:no_account';
      return (await applyAccountEvent(accountId, 'product', product?.activation_status ?? eventType.split('.').pop())) ? 'product:updated' : 'ignored:unknown_account';
    }
    default:
      return 'ignored:event';
  }
}

/**
 * Record the money, once. Locks the request row for the transaction, exits
 * if it is already paid, refuses an amount that is not the one the link was
 * issued for, and records the payment through the same bookkeeping the
 * office uses — so the invoice moves to PARTIAL or PAID exactly as before.
 */
export async function markPaid(row: PaymentRequest, payment: RzpEntity, link: RzpEntity | null): Promise<string> {
  // Razorpay delivers the same capture several ways (payment.captured,
  // order.paid, payment_link.paid) and retries each. Events about one request
  // queue behind each other in-process, so only one holds a connection and
  // the row lock at a time; the database lock still covers other instances.
  return withRequestLock(row.id, async () => {
    // Cheap exit for replays: the gateway payment is already in the books.
    const already = await prismaUnscoped.payment.findUnique({ where: { gatewayPaymentId: payment.id }, select: { id: true } });
    if (already) {
      const current = await prismaUnscoped.paymentRequest.findUnique({ where: { id: row.id }, select: { status: true } });
      if (current && current.status !== PaymentRequestStatus.PAID) {
        await prismaUnscoped.paymentRequest.update({ where: { id: row.id }, data: { status: PaymentRequestStatus.PAID, paymentId: already.id, gatewayPaymentId: payment.id } }).catch(() => {});
      }
      return 'duplicate:payment_exists';
    }
    return markPaidLocked(row, payment, link);
  });
}

const requestLocks = new Map<string, Promise<unknown>>();
async function withRequestLock<T>(key: string, fn: () => Promise<T>): Promise<T> {
  const previous = requestLocks.get(key) ?? Promise.resolve();
  const run = previous.catch(() => undefined).then(fn);
  requestLocks.set(key, run);
  try {
    return await run;
  } finally {
    if (requestLocks.get(key) === run) requestLocks.delete(key);
  }
}

async function markPaidLocked(row: PaymentRequest, payment: RzpEntity, link: RzpEntity | null): Promise<string> {
  const tenantId = row.tenantId;
  const student = await prismaUnscoped.studentProfile.findUnique({ where: { id: row.studentProfileId }, select: { userId: true } });
  const ctx = { tenantId, userId: student?.userId ?? row.createdById ?? 'webhook', role: Role.HOSTEL_ADMIN };

  const outcome = await runWithTenantContext(ctx, () =>
    db.$transaction(async (tx) => {
      await tx.$executeRaw`SELECT id FROM "PaymentRequest" WHERE id = ${row.id} FOR UPDATE`;
      const fresh = await tx.paymentRequest.findFirst({ where: { id: row.id } });
      if (!fresh) return { result: 'ignored:no_request', paymentId: null as string | null };
      if (fresh.status === PaymentRequestStatus.PAID) return { result: 'duplicate:already_paid', paymentId: null as string | null };

      // The captured amount must be what the link asked for. Anything else is
      // a problem for a person, not something to book silently.
      if (typeof payment.amount === 'number' && payment.amount !== fresh.amountPaise) {
        await tx.paymentRequest.update({
          where: { id: fresh.id },
          data: { status: PaymentRequestStatus.FAILED, latestError: `Amount mismatch: gateway captured ${payment.amount} paise, link was for ${fresh.amountPaise}`, gatewayPaymentId: payment.id },
        });
        return { result: 'rejected:amount_mismatch', paymentId: null as string | null };
      }

      // The same gateway payment seen through another event: already booked.
      const dup = await tx.payment.findFirst({ where: { gatewayPaymentId: payment.id } });
      if (dup) {
        await tx.paymentRequest.update({ where: { id: fresh.id }, data: { status: PaymentRequestStatus.PAID, paidAt: dup.paidAt, paymentId: dup.id, gatewayPaymentId: payment.id } });
        return { result: 'duplicate:payment_exists', paymentId: null as string | null };
      }

      const invoice = await tx.invoice.findFirst({ where: { id: fresh.invoiceId }, include: { payments: { where: { status: PaymentStatus.CLEARED }, select: { amount: true } } } });
      if (!invoice) return { result: 'ignored:no_invoice', paymentId: null as string | null };
      const paidAt = payment.created_at ? new Date(payment.created_at * 1000) : new Date();
      const feeAmount = fresh.gatewayFee + fresh.gatewayFeeTax + fresh.routeFee + fresh.routeFeeTax;
      const created = await tx.payment.create({
        data: {
          tenantId,
          invoiceId: invoice.id,
          // The invoice is credited with the base: a student-borne fee is the
          // gateway's, not the hostel's income.
          amount: fresh.baseAmount,
          method: 'ONLINE',
          reference: payment.id,
          note: `Paid online${payment.method ? ` by ${payment.method.toUpperCase()}` : ''}`,
          recordedById: ctx.userId,
          paidAt,
          gatewayProvider: 'razorpay',
          gatewayPaymentId: payment.id,
          gatewayOrderId: payment.order_id ?? null,
          gatewayLinkId: fresh.linkId ?? link?.id ?? null,
          // Ids and amounts only; never the payer's contact or instrument details.
          gatewayPayload: { id: payment.id, amount: payment.amount ?? null, status: payment.status ?? null, method: payment.method ?? null, order_id: payment.order_id ?? null, created_at: payment.created_at ?? null },
          feeAmount,
          netAmount: fresh.feeBearer === FeeBearer.STUDENT ? fresh.baseAmount : fresh.baseAmount - feeAmount,
        },
        select: { id: true },
      });
      const paidSoFar = invoice.payments.reduce((n, p) => n + p.amount, 0) + fresh.baseAmount;
      await tx.invoice.update({
        where: { id: invoice.id },
        data: paidSoFar >= invoice.amount ? { status: InvoiceStatus.PAID, paidAt } : { status: InvoiceStatus.PARTIAL },
      });
      await tx.paymentRequest.update({
        where: { id: fresh.id },
        data: { status: PaymentRequestStatus.PAID, paidAt, paymentId: created.id, gatewayPaymentId: payment.id, latestError: null },
      });
      return { result: 'recorded', paymentId: created.id };
    }, { maxWait: 15_000, timeout: 30_000 }),
  );

  // Side effects after commit: the receipt email the office's own payments send.
  if (outcome.paymentId) {
    const paymentId = outcome.paymentId;
    notify.inBackground('online payment received', () => notify.notifyPaymentRecorded(tenantId, paymentId));
  }
  return outcome.result;
}

/** A refund processed at Razorpay: the money went back, so the payment is reversed in the books. */
async function reverseForRefund(gatewayPaymentId: string, amountPaise: number | null, refundId: string | null): Promise<string> {
  const payment = await prismaUnscoped.payment.findUnique({ where: { gatewayPaymentId } });
  if (!payment) return 'ignored:unknown_payment';
  if (payment.status === PaymentStatus.FAILED) return 'duplicate:already_reversed';
  const ctx = { tenantId: payment.tenantId, userId: payment.recordedById, role: Role.HOSTEL_ADMIN };
  await runWithTenantContext(ctx, async () => {
    await failPayment(payment.id, `Refunded via Razorpay${refundId ? ` (${refundId})` : ''}${amountPaise != null ? ` · ₹${Math.round(amountPaise / 100)}` : ''}`);
  });
  await prismaUnscoped.payment.update({
    where: { id: payment.id },
    data: { refundId: refundId ?? payment.refundId, refundStatus: 'PROCESSED', refundedAt: new Date(), refundAmount: amountPaise != null ? Math.round(amountPaise / 100) : payment.refundAmount ?? payment.amount },
  });
  const tenantId = payment.tenantId;
  notify.inBackground('online payment refunded', () => notify.notifyPaymentFailed(tenantId, payment.id));
  return 'reversed:refund';
}
