import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { InvoiceStatus, InvoiceType, Role } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { authorize } from '../../middleware/authorize';
import { requireFeature } from '../../middleware/requireFeature';
import { requirePermission } from '../../middleware/requirePermission';
import { propertyContext } from '../../middleware/propertyContext';
import { isValidPeriod } from '../../lib/period';
import { BadRequestError } from '../../lib/errors';
import * as svc from './billing.service';
import { buildInvoicePdf } from './invoice-pdf.service';
import { getPagination, getSearch } from '../../lib/pagination';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import * as notify from '../notifications/notifications.service';
import { FeeBearer } from '@prisma/client';
import { db } from '../../lib/prisma';
import * as links from '../payments/payment-requests.service';
import { onlineCollectionFor } from '../payments/payment-account.service';
import { getVirtualAccount, requestRefund } from '../payments/collections.service';
import { refundSchema } from '../payments/collections.routes';

const generateSchema = z.object({
  period: z.string().refine(isValidPeriod, 'period must be YYYY-MM'),
  type: z.nativeEnum(InvoiceType),
});
const paySchema = z.object({
  amount: z.coerce.number().int().positive(),
  method: z.enum(['CASH', 'UPI', 'CARD', 'BANK_TRANSFER', 'CHEQUE', 'OTHER']),
  note: z.string().max(200).optional(),
  // UPI/UTR, card slip or cheque number. Optional so older clients that do
  // not send it keep working.
  reference: z.string().trim().max(80).optional(),
  // When the money was actually received (offline payments are often entered
  // later). YYYY-MM-DD, not in the future. Omitted means now.
  paidAt: z
    .string()
    .regex(/^\d{4}-\d{2}-\d{2}$/, 'paidAt must be YYYY-MM-DD')
    .optional()
    .transform((v) => (v ? new Date(`${v}T12:00:00.000Z`) : undefined))
    .refine((d) => !d || !Number.isNaN(d.getTime()), 'paidAt is not a date')
    .refine((d) => !d || d.getTime() <= Date.now() + 36 * 60 * 60 * 1000, 'paidAt cannot be in the future'),
});

export const billingRouter = Router();

// ── Student self-service: own dues ─────────────────────────────────────────
const myDuesQuery = z.object({
  year: z.string().regex(/^\d{4}$/, 'year must be YYYY').optional(),
  type: z.nativeEnum(InvoiceType).optional(),
  // Query strings carry no booleans, so the presence of "true" is the signal.
  unpaidOnly: z.enum(['true', 'false']).optional(),
});

billingRouter.get(
  '/my-dues',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    const parsed = myDuesQuery.safeParse(req.query);
    if (!parsed.success) throw new BadRequestError(parsed.error.issues[0].message);

    const result = await svc.getMyDues(
      req.user!.sub,
      {
        year: parsed.data.year,
        type: parsed.data.type,
        unpaidOnly: parsed.data.unpaidOnly === 'true',
      },
      getPagination(req.query),
    );

    // Additive: whether this hostel takes online payments, and the live link
    // on each unpaid row. Old builds ignore both.
    const online = await onlineCollectionFor(getTenantIdOrThrow());
    const rows = (Array.isArray(result) ? result : result.items) as Array<{ id: string }>;
    const live = online.enabled ? await links.liveLinksFor(rows.map((r) => r.id)) : new Map();
    for (const r of rows) Object.assign(r, { paymentLink: live.get(r.id) ?? null, canPayOnline: online.enabled });
    // Smart Collect: the student's own bank-transfer details, when issued.
    const profile = await db.studentProfile.findFirst({ where: { userId: req.user!.sub }, select: { id: true } });
    const virtualAccount = profile ? await getVirtualAccount(profile.id) : null;

    // An array keeps the pre-pagination shape; an envelope is passed straight
    // through, so a paging client reads `invoices.items`.
    res.json({ invoices: result, onlineCollection: online.enabled, virtualAccount });
  }),
);

/**
 * A student's own invoice as a PDF.
 *
 * The web prints its own DOM, which has no mobile equivalent — so the
 * document is rendered server-side and both clients download the same bytes.
 * Ownership is enforced in the service, not here.
 */
billingRouter.get(
  '/my-dues/:id/pdf',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    const { buffer, filename } = await buildInvoicePdf(req.params.id, { userId: req.user!.sub });
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
    res.send(buffer);
  }),
);

/** Every payment the student has made, newest first. `page` opts into an envelope. */
billingRouter.get(
  '/my-dues/payments',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    const pagination = getPagination(req.query);
    const result = await svc.getMyPayments(req.user!.sub, pagination);
    res.json(pagination ? result : { payments: result });
  }),
);

/** The ledger's four figures, which a page cannot supply. */
billingRouter.get(
  '/my-dues/stats',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ stats: await svc.getMyDuesStats(req.user!.sub) });
  }),
);

/**
 * Pay an invoice online: a hosted Razorpay link for exactly what is owed.
 * Idempotent — pressing Pay twice returns the same live link.
 */
billingRouter.post(
  '/my-dues/:id/pay',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    res.status(201).json({ paymentRequest: await links.createOrReuseRequest(req.params.id, { origin: 'STUDENT', studentUserId: req.user!.sub }) });
  }),
);

/** The year filter's options, which a single page cannot supply. */
billingRouter.get(
  '/my-dues/years',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ years: await svc.getMyDuesYears(req.user!.sub) });
  }),
);

// ── Rent management: invoices + payments (needs MANAGE_RENT) ────────────────
const adminOnly = [authenticate, requireFeature('billing'), propertyContext, requirePermission('MANAGE_RENT')] as const;

/**
 * Any invoice in the property, as a PDF. Staff reach the same document the
 * student does — one layout, so a receipt cannot differ by who printed it.
 */
billingRouter.get(
  '/:id/pdf',
  ...adminOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const { buffer, filename } = await buildInvoicePdf(req.params.id);
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
    res.send(buffer);
  }),
);

billingRouter.post(
  '/generate',
  ...adminOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const { period, type } = generateSchema.parse(req.body);
    const result = type === InvoiceType.RENT ? await svc.generateRentInvoices(period) : await svc.generateMessInvoices(period);
    const { createdIds, ...body } = result;
    res.status(201).json(body);
    // "Fee due" emails, after the response: a run can be hundreds of students.
    const tenantId = getTenantIdOrThrow();
    notify.inBackground('invoices raised', () => notify.notifyInvoicesRaised(tenantId, createdIds));
  }),
);

/**
 * What a mess month would cost, without writing anything. Under actual-cost
 * the rate is not knowable in advance, and under any mode an admin wants the
 * number before it becomes invoices.
 */
billingRouter.get(
  '/mess-preview',
  authenticate,
  requireFeature('billing'),
  propertyContext,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const period = typeof req.query.period === 'string' ? req.query.period : '';
    if (!/^\d{4}-\d{2}$/.test(period)) throw new BadRequestError('period (YYYY-MM) is required');
    res.json({ preview: await svc.previewMessBilling(period) });
  }),
);

billingRouter.get(
  '/',
  ...adminOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const period = typeof req.query.period === 'string' ? req.query.period : undefined;
    if (period && !isValidPeriod(period)) throw new BadRequestError('period must be YYYY-MM');
    const type = req.query.type as InvoiceType | undefined;
    const status = req.query.status as InvoiceStatus | undefined;
    const pagination = getPagination(req.query);
    const result = await svc.listInvoices(
      { period, type, status, propertyId: req.propertyId, q: getSearch(req.query) },
      pagination,
    );
    // Additive: the live payment link on each row, when online collection is on.
    const rows = (pagination ? (result as { items: Array<{ id: string }> }).items : (result as Array<{ id: string }>)) ?? [];
    const live = await links.liveLinksFor(rows.map((r) => r.id));
    for (const r of rows) Object.assign(r, { paymentLink: live.get(r.id) ?? null });
    res.json(pagination ? result : { invoices: result });
  }),
);

/** What a student would be charged online, under each fee bearer, before anything is sent. */
billingRouter.post(
  '/fee-preview',
  ...adminOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const { amount } = z.object({ amount: z.coerce.number().int().min(1).max(10_000_000) }).parse(req.body);
    const settings = await db.tenantSettings.findFirst({ select: { feeBearer: true } });
    res.json({
      current: settings?.feeBearer ?? FeeBearer.STUDENT,
      student: links.feeBreakdown(amount, FeeBearer.STUDENT),
      hostel: links.feeBreakdown(amount, FeeBearer.HOSTEL),
    });
  }),
);

/**
 * Links for every unpaid invoice in a period, emailed in one go. Each link
 * is created (or reused) and sent on its own, so one student's bounce does
 * not stop the rest; the counts say what happened.
 */
billingRouter.post(
  '/payment-links/send-unpaid',
  ...adminOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const { period } = z.object({ period: z.string().refine(isValidPeriod, 'period must be YYYY-MM') }).parse(req.body);
    const unpaid = await svc.listInvoices({ period, status: undefined, propertyId: req.propertyId });
    const rows = (unpaid as Array<{ id: string; status: string }>).filter((i) => i.status !== 'PAID');
    const result = { invoices: rows.length, linked: 0, sent: 0, failed: 0, errors: [] as string[] };
    for (const inv of rows) {
      try {
        const r = await links.createOrReuseRequest(inv.id, { origin: 'OFFICE', createdById: req.user!.sub });
        result.linked++;
        const sent = await links.sendRequest(r.id);
        if (sent.emailed || sent.messaged) result.sent++;
        else result.failed++;
      } catch (e) {
        result.failed++;
        if (result.errors.length < 5) result.errors.push(e instanceof Error ? e.message : String(e));
      }
    }
    res.json({ result });
  }),
);

// Literal path before the param route below, or '/:id' swallows it.
billingRouter.get(
  '/summary',
  ...adminOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const period = typeof req.query.period === 'string' ? req.query.period : undefined;
    if (period && !isValidPeriod(period)) throw new BadRequestError('period must be YYYY-MM');
    res.json({
      summary: await svc.invoiceSummary({
        period,
        type: req.query.type as InvoiceType | undefined,
        status: req.query.status as InvoiceStatus | undefined,
        propertyId: req.propertyId,
        q: getSearch(req.query),
      }),
    });
  }),
);

/**
 * One invoice, shaped as a row of the list (Sprint L1). A client that holds
 * an id — a receipt on the collections view, a row just paid online — reads
 * it here instead of downloading the month to find it. After every literal
 * GET above, so it swallows none of them.
 */
billingRouter.get(
  '/:id',
  ...adminOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const invoice = await svc.getInvoice(req.params.id, req.propertyId);
    const live = await links.liveLinksFor([invoice.id]);
    res.json({ invoice: { ...invoice, paymentLink: live.get(invoice.id) ?? null } });
  }),
);

billingRouter.delete(
  '/:id',
  ...adminOnly,
  asyncHandler(async (req: Request, res: Response) => {
    await svc.deleteInvoice(req.params.id);
    res.status(204).send();
  }),
);

billingRouter.post(
  '/:id/pay',
  ...adminOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const input = paySchema.parse(req.body);
    const { invoice, paymentId } = await svc.recordPayment(req.params.id, input, req.user!.sub);
    res.status(201).json({ invoice });
    const tenantId = getTenantIdOrThrow();
    notify.inBackground('payment received', () => notify.notifyPaymentRecorded(tenantId, paymentId));
  }),
);

/**
 * A payment link for the office: created or reused, and emailed when asked.
 * The link always asks for the current balance.
 */
billingRouter.post(
  '/:id/payment-link',
  ...adminOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const { send } = z.object({ send: z.boolean().optional().default(false) }).parse(req.body ?? {});
    const r = await links.createOrReuseRequest(req.params.id, { origin: 'OFFICE', createdById: req.user!.sub });
    res.status(201).json({ paymentRequest: send ? await links.sendRequest(r.id) : r });
  }),
);

/** Every payment on an invoice, reversed ones included. */
billingRouter.get(
  '/:id/payments',
  ...adminOnly,
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ payments: await svc.listInvoicePayments(req.params.id) });
  }),
);

/**
 * Refund an online payment through Razorpay. The books change when Razorpay
 * confirms (webhook or reconciliation); until then the row reads "requested".
 */
billingRouter.post(
  '/payments/:paymentId/refund',
  ...adminOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const input = refundSchema.parse(req.body);
    const payment = await requestRefund(req.params.paymentId, input, req.user!.sub);
    res.json({ payment: { id: payment.id, refundId: payment.refundId, refundStatus: payment.refundStatus, refundAmount: payment.refundAmount, refundRequestedAt: payment.refundRequestedAt } });
  }),
);

/** A payment that did not go through: reverse it and tell the student. */
billingRouter.post(
  '/payments/:paymentId/fail',
  ...adminOnly,
  asyncHandler(async (req: Request, res: Response) => {
    const { reason } = z.object({ reason: z.string().trim().max(200).optional() }).parse(req.body ?? {});
    const { invoice, paymentId } = await svc.failPayment(req.params.paymentId, reason);
    res.json({ invoice });
    const tenantId = getTenantIdOrThrow();
    notify.inBackground('payment failed', () => notify.notifyPaymentFailed(tenantId, paymentId));
  }),
);
