import type { Prisma } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { router, withPermission } from '../trpc';

const dateStr = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be YYYY-MM-DD');
const monthStr = z.string().regex(/^\d{4}-\d{2}$/, 'Month must be YYYY-MM');

/** The reports the office lays out itself, each with its own saved layouts. */
const LAID_OUT = z.enum(['outstanding-invoices']);

/** The layouts a person sees: their own, and the ones shared with the office. */
const visibleLayouts = (organizationId: string, userId: string): Prisma.ReportLayoutWhereInput => ({
  organizationId,
  OR: [{ ownerId: userId }, { ownerId: null }],
});

export const reportsRouter = router({
  trialBalance: withPermission('finance.report')
    .input(z.object({ asOf: dateStr }))
    .query(({ ctx, input }) => ctx.reports.trialBalance(ctx.organizationId ?? '', input.asOf)),

  arAging: withPermission('finance.report')
    .input(z.object({ asOf: dateStr, tenantIds: z.array(z.string()).optional() }))
    .query(({ ctx, input }) => ctx.reports.arAging(ctx.organizationId ?? '', input.asOf, input.tenantIds)),

  outstandingInvoices: withPermission('finance.report')
    .input(
      z.object({
        asOf: dateStr,
        settlement: z.array(z.enum(['UNSETTLED', 'PARTIAL', 'SETTLED'])),
        includeUnissued: z.boolean(),
        issueFrom: dateStr.optional(),
        issueTo: dateStr.optional(),
        dueFrom: dateStr.optional(),
        dueTo: dateStr.optional(),
        periodFrom: monthStr.optional(),
        periodTo: monthStr.optional(),
      }),
    )
    .query(({ ctx, input }) => ctx.reports.outstandingInvoices(ctx.organizationId ?? '', input)),

  /** The leases a statement run would print, with their totals, whether this
   *  period's statement has been sent, and whether the tenant can sign in to
   *  the portal to read it. The lines themselves are left out — the statements
   *  are read as PDFs, which /api/documents/statements renders from the same
   *  figures. */
  statements: withPermission('finance.report')
    .input(z.object({ from: dateStr, to: dateStr }))
    .query(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const out = await ctx.reports.statements(organizationId, { ...input, agingBasis: 'due', openingItems: false, groupEntries: true });
      const sent = new Map((await ctx.statements.forPeriod(organizationId, input.from, input.to)).map((r) => [r.leaseId, { id: r.id, sentAt: r.sentAt }]));
      const logins = await ctx.prisma.user.findMany({
        where: { tenantId: { in: [...new Set(out.statements.map((s) => s.tenantId))] }, isActive: true },
        select: { tenantId: true },
      });
      const canSignIn = new Set(logins.map((u) => u.tenantId));
      return {
        ...out,
        statements: out.statements.map(({ rows: _rows, ...s }) => ({ ...s, sent: sent.get(s.leaseId) ?? null, portalLogin: canSignIn.has(s.tenantId) })),
      };
    }),

  /** Sends the leases' statements for the period to their tenants' portal —
   *  each rendered and kept as sent, replacing one sent before for the same
   *  period — and notifies each tenant. */
  sendStatements: withPermission('finance.report')
    .input(
      z.object({
        from: dateStr,
        to: dateStr,
        agingBasis: z.enum(['due', 'issue']),
        openingItems: z.boolean(),
        groupEntries: z.boolean(),
        leaseIds: z.array(z.string()).min(1).max(2000),
      }),
    )
    .mutation(({ ctx, input }) => ctx.statements.send({ organizationId: ctx.organizationId ?? '', query: input, sentById: ctx.user.id })),

  /** Takes a sent statement back out of the tenant's portal. */
  withdrawStatement: withPermission('finance.report')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      await ctx.statements.withdraw(ctx.organizationId ?? '', input.id);
      return { ok: true };
    }),

  incomeStatement: withPermission('finance.report')
    .input(z.object({ from: dateStr, to: dateStr }))
    .query(({ ctx, input }) => ctx.reports.incomeStatement(ctx.organizationId ?? '', input.from, input.to)),

  rentRoll: withPermission('finance.report').query(({ ctx }) => ctx.reports.rentRoll(ctx.organizationId ?? '')),

  collections: withPermission('finance.report')
    .input(z.object({ from: dateStr, to: dateStr }))
    .query(({ ctx, input }) => ctx.reports.collections(ctx.organizationId ?? '', input.from, input.to)),

  /** The landing page's KPI tiles. The month comes from the client, as every
   * report above takes its dates from the client rather than the server's clock. */
  dashboard: withPermission('finance.report')
    .input(z.object({ month: z.string().regex(/^\d{4}-\d{2}$/, 'Month must be YYYY-MM') }))
    .query(({ ctx, input }) => ctx.reports.dashboard(ctx.organizationId ?? '', input.month)),

  /** A report's saved layouts: the caller's own, and the office's shared ones.
   *  What a layout holds is the admin app's business; it is stored as given. */
  layouts: withPermission('finance.report')
    .input(z.object({ report: LAID_OUT }))
    .query(async ({ ctx, input }) => {
      const rows = await ctx.prisma.reportLayout.findMany({
        where: { ...visibleLayouts(ctx.organizationId ?? '', ctx.user.id), report: input.report },
        orderBy: { name: 'asc' },
      });
      return rows.map((r) => ({ id: r.id, name: r.name, shared: r.ownerId === null, config: r.config }));
    }),

  /** Saves a layout, new or over one the caller can see. Anyone who runs the
   *  report may keep a shared one up to date; sharing a personal one moves it,
   *  and un-sharing a shared one makes it the caller's. */
  saveLayout: withPermission('finance.report')
    .input(
      z.object({
        id: z.string().optional(),
        report: LAID_OUT,
        name: z.string().trim().min(1).max(80),
        shared: z.boolean(),
        config: z.record(z.unknown()),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const ownerId = input.shared ? null : ctx.user.id;
      const dup = await ctx.prisma.reportLayout.findFirst({
        where: { organizationId, report: input.report, ownerId, name: input.name, id: input.id ? { not: input.id } : undefined },
        select: { id: true },
      });
      if (dup) throw new TRPCError({ code: 'CONFLICT', message: 'A layout with that name already exists' });
      const data = { name: input.name, ownerId, config: input.config as Prisma.InputJsonObject };
      if (!input.id) {
        const row = await ctx.prisma.reportLayout.create({ data: { organizationId, report: input.report, ...data } });
        return { id: row.id };
      }
      const claimed = await ctx.prisma.reportLayout.updateMany({
        where: { ...visibleLayouts(organizationId, ctx.user.id), id: input.id, report: input.report },
        data,
      });
      if (claimed.count !== 1) throw new TRPCError({ code: 'NOT_FOUND', message: 'Report layout not found' });
      return { id: input.id };
    }),

  deleteLayout: withPermission('finance.report')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const gone = await ctx.prisma.reportLayout.deleteMany({ where: { ...visibleLayouts(ctx.organizationId ?? '', ctx.user.id), id: input.id } });
      if (gone.count !== 1) throw new TRPCError({ code: 'NOT_FOUND', message: 'Report layout not found' });
      return { ok: true };
    }),
});
