import { HttpException } from '@nestjs/common';
import type { PrismaClient } from '@prisma/client';
import { json, type Request, type Response, Router } from 'express';
import { z } from 'zod';
import type { AuthService } from '../auth/auth.service';
import { PRE_ISSUE_STATUSES as PRE_ISSUE } from '../billing/invoice-status';
import { hkIsoDay } from '../common/hk-date';
import type { ReportsService } from '../reports/reports.service';
import type { StatementsService } from '../statements/statements.service';
import type { AuthUser } from '../trpc/auth-user';
import type { DocumentService } from './document.service';

const day = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);

/** A statement run: the period, the options it is drawn up with, and the
 *  leases — in the order they print. */
const StatementRun = z.object({
  from: day,
  to: day,
  agingBasis: z.enum(['due', 'issue']),
  openingItems: z.boolean(),
  groupEntries: z.boolean(),
  leaseIds: z.array(z.string()).min(1).max(2000),
});

/**
 * Raw Express routes for generated PDFs — tRPC is JSON-only, so bytes go through
 * here, mirroring the uploads adapter. Mounted at /api/documents from main.ts.
 *
 * Preview and download are the same render; only the Content-Disposition differs,
 * so what a user checks on screen is exactly what the tenant receives.
 */
export function createDocumentsRouter(
  prisma: PrismaClient,
  authService: AuthService,
  documents: DocumentService,
  reports: ReportsService,
  statements: StatementsService,
) {
  const router = Router();
  // Mounted with app.use() outside the Nest pipeline, so it parses its own JSON
  // rather than assuming the global body parser reached here.
  router.use(json({ limit: '1mb' }));

  async function authenticate(req: Request): Promise<{ user: AuthUser; organizationId: string } | null> {
    // Bearer only. An <iframe> cannot carry a header, but the clients don't need
    // it to: they fetch the bytes and hand the viewer a blob URL. A token in the
    // query string would be a full session credential in browser history,
    // referrers and every proxy log along the way.
    const header = req.headers.authorization;
    const token = header?.startsWith('Bearer ') ? header.slice(7) : null;
    const user = token ? await authService.verifyAndLoad(token) : null;
    if (!user) return null;
    const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true } });
    if (!org) return null;
    return { user, organizationId: org.id };
  }

  /** A tenant may print their own issued notes; staff need invoice.read. */
  async function assertInvoiceAccess(user: AuthUser, organizationId: string, invoiceId: string): Promise<void> {
    const invoice = await prisma.invoice.findFirst({
      where: { id: invoiceId, organizationId },
      select: { status: true, lease: { select: { tenantId: true } } },
    });
    if (!invoice) throw new HttpException('Debit note not found', 404);
    if (user.tenantId) {
      if (invoice.lease.tenantId !== user.tenantId) throw new HttpException('Not your debit note', 403);
      // Drafts and notes still in approval are internal.
      if (PRE_ISSUE.includes(invoice.status)) throw new HttpException('Debit note not found', 404);
      return;
    }
    if (!user.permissions.includes('invoice.read')) throw new HttpException('Missing permission', 403);
  }

  /** A tenant may print the receipts of their own payments; staff need
   *  receipt.read. Someone else's reads as not there, as a debit note does. */
  async function receiptAccess(user: AuthUser, organizationId: string, receiptId: string): Promise<{ number: string }> {
    const receipt = await prisma.receipt.findFirst({ where: { id: receiptId, organizationId }, select: { number: true, tenantId: true } });
    if (!receipt || (user.tenantId && receipt.tenantId !== user.tenantId)) throw new HttpException('Receipt not found', 404);
    if (!user.tenantId && !user.permissions.includes('receipt.read')) throw new HttpException('Missing permission', 403);
    return receipt;
  }

  function sendPdf(res: Response, pdf: Buffer, filename: string, download: boolean): void {
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Length', String(pdf.length));
    res.setHeader('Content-Disposition', `${download ? 'attachment' : 'inline'}; filename="${filename}"`);
    res.end(pdf);
  }

  // GET /api/documents/invoice/:invoiceId.pdf[?download=1]
  router.get('/invoice/:invoiceId.pdf', async (req: Request, res: Response) => {
    try {
      const ctx = await authenticate(req);
      if (!ctx) return res.status(401).json({ error: 'Unauthorized' });
      const invoiceId = String(req.params.invoiceId);
      await assertInvoiceAccess(ctx.user, ctx.organizationId, invoiceId);
      const pdf = await documents.invoicePdf(ctx.organizationId, invoiceId);
      const { doc } = await documents.invoiceContext(ctx.organizationId, invoiceId);
      return sendPdf(res, pdf, `${doc.number}.pdf`, req.query.download === '1');
    } catch (err) {
      return sendError(res, err);
    }
  });

  // GET /api/documents/receipt/:receiptId.pdf[?download=1]
  router.get('/receipt/:receiptId.pdf', async (req: Request, res: Response) => {
    try {
      const ctx = await authenticate(req);
      if (!ctx) return res.status(401).json({ error: 'Unauthorized' });
      const receiptId = String(req.params.receiptId);
      const { number } = await receiptAccess(ctx.user, ctx.organizationId, receiptId);
      const pdf = await documents.receiptPdf(ctx.organizationId, receiptId);
      return sendPdf(res, pdf, `${number}.pdf`, req.query.download === '1');
    } catch (err) {
      return sendError(res, err);
    }
  });

  // POST /api/documents/statements  { from, to, agingBasis, openingItems, groupEntries, leaseIds }
  // The leases' statements as one PDF, each from a new page. A POST because a
  // month's run names hundreds of leases.
  router.post('/statements', async (req: Request, res: Response) => {
    try {
      const ctx = await authenticate(req);
      if (!ctx) return res.status(401).json({ error: 'Unauthorized' });
      if (!ctx.user.permissions.includes('finance.report')) return res.status(403).json({ error: 'Missing permission' });
      const run = StatementRun.safeParse(req.body);
      if (!run.success) return res.status(400).json({ error: 'Invalid statement request' });
      const { statements } = await reports.statements(ctx.organizationId, run.data);
      const order = new Map(run.data.leaseIds.map((id, i) => [id, i]));
      statements.sort((a, b) => order.get(a.leaseId)! - order.get(b.leaseId)!);
      if (statements.length === 0) return res.status(404).json({ error: 'Nothing to print for these leases in this period' });
      const pdf = await documents.statementsPdf(ctx.organizationId, statements, run.data);
      const name = statements.length === 1 ? `statement-${statements[0].leaseReference}-${run.data.to}` : `statements-${run.data.to}`;
      return sendPdf(res, pdf, `${name}.pdf`, false);
    } catch (err) {
      return sendError(res, err);
    }
  });

  // GET /api/documents/statement/:id.pdf
  // A statement as it was sent: its tenant may read it, and staff who see reports.
  router.get('/statement/:id.pdf', async (req: Request, res: Response) => {
    try {
      const ctx = await authenticate(req);
      if (!ctx) return res.status(401).json({ error: 'Unauthorized' });
      const { pdf, filename, tenantId } = await statements.file(ctx.organizationId, String(req.params.id));
      const allowed = ctx.user.tenantId ? ctx.user.tenantId === tenantId : ctx.user.permissions.includes('finance.report');
      // Someone else's statement reads as not there, as a debit note does.
      if (!allowed) return res.status(ctx.user.tenantId ? 404 : 403).json({ error: ctx.user.tenantId ? 'Statement not found' : 'Missing permission' });
      return sendPdf(res, pdf, filename, false);
    } catch (err) {
      return sendError(res, err);
    }
  });

  // POST /api/documents/preview  { docType?, invoiceId | leaseId | receiptId, body? }
  // Renders an UNSAVED template body, so the editor can show what a change does
  // before it is committed. A statement is previewed for the lease over the
  // last two months and this one to date.
  router.post('/preview', async (req: Request, res: Response) => {
    try {
      const ctx = await authenticate(req);
      if (!ctx) return res.status(401).json({ error: 'Unauthorized' });
      if (!ctx.user.permissions.includes('setting.update')) {
        return res.status(403).json({ error: 'Missing permission' });
      }
      const input = req.body as { docType?: string; invoiceId?: string; leaseId?: string; receiptId?: string; body?: string };
      const body = typeof input?.body === 'string' ? input.body : undefined;
      if (input?.docType === 'RECEIPT') {
        const receiptId = String(input.receiptId ?? '');
        if (!receiptId) return res.status(400).json({ error: 'receiptId is required' });
        return sendPdf(res, await documents.receiptPdf(ctx.organizationId, receiptId, body), 'preview.pdf', false);
      }
      if (input?.docType === 'STATEMENT') {
        const leaseId = String(input.leaseId ?? '');
        if (!leaseId) return res.status(400).json({ error: 'leaseId is required' });
        const to = hkIsoDay(new Date());
        const [y, m] = to.split('-').map(Number);
        const start = new Date(Date.UTC(y, m - 3, 1));
        const from = `${start.getUTCFullYear()}-${String(start.getUTCMonth() + 1).padStart(2, '0')}-01`;
        const range = { from, to };
        const { statements } = await reports.statements(ctx.organizationId, {
          ...range,
          agingBasis: 'due',
          openingItems: false,
          groupEntries: true,
          leaseIds: [leaseId],
        });
        if (statements.length === 0) return res.status(404).json({ error: 'Nothing to print for these leases in this period' });
        return sendPdf(res, await documents.statementsPdf(ctx.organizationId, statements, range, body), 'preview.pdf', false);
      }
      const invoiceId = String(input?.invoiceId ?? '');
      if (!invoiceId) return res.status(400).json({ error: 'invoiceId is required' });
      const pdf = await documents.invoicePdf(ctx.organizationId, invoiceId, body);
      return sendPdf(res, pdf, 'preview.pdf', false);
    } catch (err) {
      return sendError(res, err);
    }
  });

  return router;
}

function sendError(res: Response, err: unknown): Response {
  if (err instanceof HttpException) {
    const body = err.getResponse();
    return res.status(err.getStatus()).json(typeof body === 'string' ? { error: body } : body);
  }
  const message = err instanceof Error ? err.message : 'Could not generate the document';
  return res.status(500).json({ error: message });
}
