import { z } from 'zod';
import { router, withPermission } from '../trpc';

const DOC_TYPES = ['INVOICE', 'STATEMENT', 'RECEIPT'] as const;

/**
 * The layout a document prints with, as editable data. Rendering a preview
 * returns bytes, so that lives on /api/documents — this is only the text.
 */
export const documentTemplatesRouter = router({
  get: withPermission('setting.read')
    .input(z.object({ docType: z.enum(DOC_TYPES).default('INVOICE') }).optional())
    .query(({ ctx, input }) => ctx.documents.template(ctx.organizationId ?? '', input?.docType ?? 'INVOICE')),

  save: withPermission('setting.update')
    .input(
      z.object({
        docType: z.enum(DOC_TYPES).default('INVOICE'),
        name: z.string().min(1).optional(),
        body: z.string(),
        pageSize: z.enum(['A4', 'Letter', 'Legal']).optional(),
        marginsMm: z.string().regex(/^\d+(\.\d+)?(\s*,\s*\d+(\.\d+)?){3}$/, 'Margins must be four numbers: top,right,bottom,left').optional(),
      }),
    )
    .mutation(({ ctx, input }) => ctx.documents.saveTemplate({ organizationId: ctx.organizationId ?? '', ...input })),

  reset: withPermission('setting.update')
    .input(z.object({ docType: z.enum(DOC_TYPES).default('INVOICE') }).optional())
    .mutation(({ ctx, input }) => ctx.documents.resetTemplate(ctx.organizationId ?? '', input?.docType ?? 'INVOICE')),

  /** Debit notes to preview a template against — newest first, any status. */
  sampleInvoices: withPermission('setting.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.invoice.findMany({
      where: { organizationId: ctx.organizationId ?? undefined },
      orderBy: { createdAt: 'desc' },
      take: 25,
      include: { lease: { select: { reference: true, tenant: { select: { name: true } } } } },
    });
    return rows.map((i) => ({
      id: i.id,
      label: `${i.number ?? `DRAFT-${i.id.slice(-6).toUpperCase()}`} · ${i.lease.tenant.name} · ${i.billingPeriod}`,
    }));
  }),

  /** Leases to preview a statement template against — those billed most recently. */
  sampleLeases: withPermission('setting.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.lease.findMany({
      where: { organizationId: ctx.organizationId ?? undefined, deletedAt: null, invoices: { some: { number: { not: null } } } },
      orderBy: { updatedAt: 'desc' },
      take: 25,
      select: { id: true, reference: true, tenant: { select: { name: true } } },
    });
    return rows.map((l) => ({ id: l.id, label: `${l.reference} · ${l.tenant.name}` }));
  }),

  /** Receipts to preview a receipt template against — only an approved
   *  payment has one — newest first, deposit receipts among them. */
  sampleReceipts: withPermission('setting.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.receipt.findMany({
      // An overpaid part prints on its payment's receipt, not on one of its own.
      where: { organizationId: ctx.organizationId ?? undefined, status: { in: ['APPROVED', 'BOUNCED'] }, sourceReceiptId: null },
      orderBy: { createdAt: 'desc' },
      take: 25,
      select: { id: true, number: true, amount: true, currency: true, tenantId: true },
    });
    const tenants = await ctx.prisma.tenant.findMany({ where: { id: { in: [...new Set(rows.map((r) => r.tenantId))] } }, select: { id: true, name: true } });
    const nameOf = new Map(tenants.map((t) => [t.id, t.name]));
    return rows.map((r) => ({ id: r.id, label: `${r.number} · ${nameOf.get(r.tenantId) ?? '—'} · ${r.currency} ${r.amount.toFixed(2)}` }));
  }),
});
