import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { Role, SubscriptionInvoiceType, SubscriptionStatus } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { authorize } from '../../middleware/authorize';
import { BadRequestError } from '../../lib/errors';
import { sendEmail, emailFailed } from '../../lib/email';
import { subscriptionInvoiceEmail } from '../../lib/email-templates';
import * as svc from './subscriptions.service';
import { buildSubscriptionInvoicePdf } from './subscription-invoice-pdf.service';

/**
 * Platform subscription billing. SUPER_ADMIN-only: this is the ledger of what
 * hostels owe US, and no tenant may read or write it here. (A hostel owner
 * reads their own issued invoices through /api/plan-usage.)
 *
 * Invoices are raised by hand (6 Oct 2026); the monthly bulk run is retired.
 */
export const subscriptionRouter = Router();
subscriptionRouter.use(authenticate, authorize(Role.SUPER_ADMIN));

const money = z.coerce.number({ invalid_type_error: 'Amount must be a number' }).int('Amount must be whole rupees').positive('Amount must be greater than zero').max(100_000_000);
/** A calendar day, YYYY-MM-DD, held at noon UTC. */
const day = z
  .string()
  .regex(/^\d{4}-\d{2}-\d{2}$/, 'Use a YYYY-MM-DD date')
  .refine((d) => !Number.isNaN(Date.parse(d)), 'Not a real date')
  .transform(svc.noonUtc);
/** Accepts a full timestamp too, for payment dates sent by older clients. */
const dateish = z
  .string()
  .refine((d) => !Number.isNaN(Date.parse(d)), 'invalid date')
  .transform((d) => (/^\d{4}-\d{2}-\d{2}$/.test(d) ? svc.noonUtc(d) : new Date(d)));
const taxRate = z.coerce
  .number({ invalid_type_error: 'Tax rate must be a number' })
  .min(0, 'Tax rate cannot be negative')
  .max(100, 'Tax rate cannot be above 100%')
  .refine((v) => Math.round(v * 100) === v * 100, 'At most two decimals');

const invoiceFields = {
  invoiceType: z.nativeEnum(SubscriptionInvoiceType),
  subtotal: money,
  taxRate,
  issueDate: day,
  dueDate: day,
  periodStart: day.nullable(),
  periodEnd: day.nullable(),
  note: z.string().trim().max(500, 'Notes can be at most 500 characters').nullable(),
};
const createSchema = z.object({ tenantId: z.string().uuid('Pick a hostel'), ...invoiceFields }).partial({
  subtotal: true,
  taxRate: true,
  issueDate: true,
  dueDate: true,
  periodStart: true,
  periodEnd: true,
  note: true,
});
const updateSchema = z.object(invoiceFields).partial().refine((v) => Object.keys(v).length > 0, 'Nothing to update');

const paymentFields = {
  amount: money,
  method: z.enum(svc.PAYMENT_METHODS),
  reference: z.string().trim().max(80).nullable().optional(),
  note: z.string().trim().max(200).nullable().optional(),
  paidAt: dateish.optional(),
};
const paySchema = z.object(paymentFields);
const ledgerPaySchema = z
  .object({ tenantId: z.string().uuid().optional(), invoiceId: z.string().uuid().optional(), ...paymentFields })
  .refine((v) => v.tenantId || v.invoiceId, 'Pick a hostel');
const markPaidSchema = z.object({ method: z.enum(svc.PAYMENT_METHODS).default('BANK_TRANSFER'), reference: paymentFields.reference, note: paymentFields.note, paidAt: dateish.optional() });

const str = (req: Request, k: string) => (typeof req.query[k] === 'string' && (req.query[k] as string) ? (req.query[k] as string) : undefined);
function dayQuery(req: Request, k: string) {
  const v = str(req, k);
  if (!v) return undefined;
  if (!/^\d{4}-\d{2}-\d{2}$/.test(v)) throw new BadRequestError(`${k} must be YYYY-MM-DD`);
  return svc.noonUtc(v);
}

const fmtDay = (d: Date | null | undefined) => (d ? d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', timeZone: 'UTC' }) : null);

/** KPI strip. */
subscriptionRouter.get(
  '/summary',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json(await svc.getSummary());
  }),
);

subscriptionRouter.get(
  '/invoices',
  asyncHandler(async (req: Request, res: Response) => {
    const status = str(req, 'status');
    if (status && !(status in SubscriptionStatus)) throw new BadRequestError('unknown status');
    const type = str(req, 'type');
    if (type && !(type in SubscriptionInvoiceType)) throw new BadRequestError('unknown invoice type');
    res.json({
      invoices: await svc.listInvoices({
        status: status as SubscriptionStatus | undefined,
        type: type as SubscriptionInvoiceType | undefined,
        tenantId: str(req, 'tenantId'),
        q: str(req, 'q'),
        from: dayQuery(req, 'from'),
        to: dayQuery(req, 'to'),
        overdue: req.query.overdue === 'true',
      }),
    });
  }),
);

/** Raise an invoice by hand. It starts as a draft. */
subscriptionRouter.post(
  '/invoices',
  asyncHandler(async (req: Request, res: Response) => {
    const input = createSchema.parse(req.body);
    res.status(201).json({ invoice: await svc.createInvoice(input, req.user!.sub) });
  }),
);

subscriptionRouter.get(
  '/invoices/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ invoice: await svc.getInvoice(req.params.id) });
  }),
);

subscriptionRouter.get(
  '/invoices/:id/pdf',
  asyncHandler(async (req: Request, res: Response) => {
    const { buffer, filename } = await buildSubscriptionInvoicePdf(req.params.id);
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', `${req.query.download === 'true' ? 'attachment' : 'inline'}; filename="${filename}"`);
    res.send(buffer);
  }),
);

subscriptionRouter.put(
  '/invoices/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ invoice: await svc.updateInvoice(req.params.id, updateSchema.parse(req.body)) });
  }),
);

/**
 * Email the PDF to the hostel and issue the invoice. A draft becomes unpaid;
 * a paid invoice is re-sent for its records without changing status. A
 * failed delivery still issues it and says so.
 */
subscriptionRouter.post(
  '/invoices/:id/send',
  asyncHandler(async (req: Request, res: Response) => {
    const current = await svc.getInvoice(req.params.id);
    if (current.status === SubscriptionStatus.VOID) throw new BadRequestError('Cancelled invoices cannot be sent');
    const buyer = await svc.buyerParty(current.tenantId);
    if (buyer.recipients.length === 0) throw new BadRequestError(`${buyer.name} has no email on file — add a billing email in their settings`);
    await svc.issueInvoice(req.params.id);
    const { buffer, filename, invoice } = await buildSubscriptionInvoicePdf(req.params.id);
    const mail = subscriptionInvoiceEmail({
      seller: invoice.seller,
      hostelName: invoice.tenant.name,
      number: invoice.invoiceNumber ?? filename.replace(/\.pdf$/, ''),
      amount: invoice.amount,
      balance: invoice.balance,
      dueDate: fmtDay(invoice.dueDate),
      description: invoice.description,
      period: invoice.periodStart || invoice.periodEnd ? `${fmtDay(invoice.periodStart) ?? '—'} – ${fmtDay(invoice.periodEnd) ?? '—'}` : null,
    });
    const result = await sendEmail(buyer.recipients[0], mail.subject, mail.text, mail.html, [{ filename, content: buffer }]);
    if (!emailFailed(result)) await svc.markSent(req.params.id);
    res.json({
      invoice: await svc.getInvoice(req.params.id),
      email: { to: buyer.recipients[0], sent: result.sent, mode: result.mode },
      message: emailFailed(result) ? `Invoice issued, but the email to ${buyer.recipients[0]} could not be delivered` : `Invoice sent to ${buyer.recipients[0]}`,
    });
  }),
);

/** Issue a draft without emailing it. */
subscriptionRouter.post(
  '/invoices/:id/issue',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ invoice: await svc.issueInvoice(req.params.id) });
  }),
);

/** Settle the whole balance in one payment. */
subscriptionRouter.post(
  '/invoices/:id/mark-paid',
  asyncHandler(async (req: Request, res: Response) => {
    const input = markPaidSchema.parse(req.body ?? {});
    const inv = await svc.getInvoice(req.params.id);
    if (inv.balance <= 0) throw new BadRequestError('Invoice is already fully paid');
    await svc.recordPayment({ invoiceId: inv.id, amount: inv.balance, ...input }, req.user!.sub);
    res.json({ invoice: await svc.getInvoice(req.params.id) });
  }),
);

/** Record a full or partial payment against this invoice. */
subscriptionRouter.post(
  '/invoices/:id/pay',
  asyncHandler(async (req: Request, res: Response) => {
    const input = paySchema.parse(req.body);
    await svc.recordPayment({ invoiceId: req.params.id, ...input }, req.user!.sub);
    res.status(201).json({ invoice: await svc.getInvoice(req.params.id) });
  }),
);

/** Cancel: kept on record, no longer billable. */
subscriptionRouter.post(
  '/invoices/:id/void',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ invoice: await svc.voidInvoice(req.params.id) });
  }),
);

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

/** Issued invoices with money still owing. */
subscriptionRouter.get(
  '/outstanding',
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await svc.outstanding(str(req, 'tenantId')));
  }),
);

/** What a new payment for this hostel can be set against. */
subscriptionRouter.get(
  '/invoice-options',
  asyncHandler(async (req: Request, res: Response) => {
    const tenantId = str(req, 'tenantId');
    if (!tenantId) throw new BadRequestError('tenantId is required');
    res.json({ invoices: await svc.invoiceOptions(tenantId) });
  }),
);

/** The cross-hostel payment ledger. */
subscriptionRouter.get(
  '/payments',
  asyncHandler(async (req: Request, res: Response) => {
    const method = str(req, 'method');
    if (method && !(svc.PAYMENT_METHODS as readonly string[]).includes(method)) throw new BadRequestError('unknown payment method');
    res.json(await svc.listPayments({ tenantId: str(req, 'tenantId'), method, q: str(req, 'q'), from: dayQuery(req, 'from'), to: dayQuery(req, 'to') }));
  }),
);

/** Record a payment against an invoice or on account. */
subscriptionRouter.post(
  '/payments',
  asyncHandler(async (req: Request, res: Response) => {
    const input = ledgerPaySchema.parse(req.body);
    res.status(201).json({ payment: await svc.recordPayment(input, req.user!.sub) });
  }),
);

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