import type { PrismaClient } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { pickedAccount } from '../../ledger/chart-of-accounts';
import { router, withPermission } from '../trpc';

/**
 * The accounts the organisation collects into. A debit note prints one of these
 * as its payment instruction, so until there was a way to create one every note
 * went out with a blank account number.
 *
 * Deleting is deliberately absent: an account named on an issued note has to
 * stay resolvable, and the note's own frozen snapshot is not the only reader —
 * the lease still points at it. Deactivating takes it out of circulation
 * without breaking anything that already refers to it.
 *
 * Each names the chart's bank account its money posts to (ledger/
 * bank-accounts.ts); one that names none posts to the chart's Bank.
 */
const accountInput = z.object({
  name: z.string().min(1).max(120),
  bankName: z.string().min(1).max(120),
  accountName: z.string().min(1).max(160),
  accountNumber: z.string().min(1).max(64),
  isCollectionAgent: z.boolean().default(false),
  isActive: z.boolean().default(true),
  /** The chart's bank account it posts to; none is the chart's Bank. Left out
   *  on an update, it stays as it is. */
  glAccountId: z.string().optional().nullable(),
});

/** A collection account's ledger account: one of the chart's bank accounts,
 *  active unless it is the one the account already has. */
async function bankGlAccount(
  prisma: PrismaClient,
  organizationId: string,
  id: string | null | undefined,
  keep?: string | null,
): Promise<string | null | undefined> {
  const picked = await pickedAccount(prisma, organizationId, id, keep);
  if (!picked) return picked;
  const account = await prisma.glAccount.findUnique({ where: { id: picked }, select: { isBank: true } });
  if (!account?.isBank) throw new TRPCError({ code: 'BAD_REQUEST', message: "A collection account posts to one of the chart's bank accounts" });
  return picked;
}

export const bankAccountsRouter = router({
  list: withPermission('bank-account.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.bankAccount.findMany({
      where: { organizationId: ctx.organizationId ?? undefined },
      orderBy: [{ isActive: 'desc' }, { isCollectionAgent: 'desc' }, { name: 'asc' }],
      include: { glAccount: { select: { code: true, name: true } } },
    });
    // How many leases point at each, so deactivating one is an informed choice.
    const counts = await ctx.prisma.lease.groupBy({
      by: ['bankAccountId'],
      where: { organizationId: ctx.organizationId ?? undefined, deletedAt: null, bankAccountId: { not: null } },
      _count: { _all: true },
    });
    const leaseCount = new Map(counts.map((c) => [c.bankAccountId, c._count._all]));
    return rows.map((r) => ({
      id: r.id,
      name: r.name,
      bankName: r.bankName,
      accountName: r.accountName,
      accountNumber: r.accountNumber,
      isCollectionAgent: r.isCollectionAgent,
      isActive: r.isActive,
      glAccountId: r.glAccountId,
      /** Its ledger account; none posts to the chart's Bank. */
      account: r.glAccount,
      leaseCount: leaseCount.get(r.id) ?? 0,
    }));
  }),

  create: withPermission('bank-account.create')
    .input(accountInput)
    .mutation(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const glAccountId = (await bankGlAccount(ctx.prisma, organizationId, input.glAccountId)) ?? null;
      if (input.isCollectionAgent) await clearOtherAgents(ctx.prisma, organizationId, null);
      const row = await ctx.prisma.bankAccount.create({ data: { ...input, glAccountId, organizationId } });
      return { id: row.id };
    }),

  update: withPermission('bank-account.update')
    .input(accountInput.extend({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const { id, ...data } = input;
      const organizationId = ctx.organizationId ?? '';
      const existing = await ctx.prisma.bankAccount.findFirst({ where: { id, organizationId }, select: { id: true, glAccountId: true } });
      if (!existing) throw new TRPCError({ code: 'NOT_FOUND', message: 'Bank account not found' });
      const glAccountId = await bankGlAccount(ctx.prisma, organizationId, data.glAccountId, existing.glAccountId);
      if (data.isCollectionAgent) await clearOtherAgents(ctx.prisma, organizationId, id);
      await ctx.prisma.bankAccount.update({ where: { id }, data: { ...data, glAccountId } });
      return { ok: true };
    }),

  setActive: withPermission('bank-account.update')
    .input(z.object({ id: z.string(), isActive: z.boolean() }))
    .mutation(async ({ ctx, input }) => {
      const claimed = await ctx.prisma.bankAccount.updateMany({
        where: { id: input.id, organizationId: ctx.organizationId ?? undefined },
        data: { isActive: input.isActive },
      });
      if (claimed.count !== 1) throw new TRPCError({ code: 'NOT_FOUND', message: 'Bank account not found' });
      return { ok: true };
    }),
});

/** Exactly one account is the default the organisation collects into, because
 *  that is what a note with no lease-specific account falls back to. */
async function clearOtherAgents(prisma: PrismaClient, organizationId: string, keepId: string | null): Promise<void> {
  await prisma.bankAccount.updateMany({
    where: { organizationId, isCollectionAgent: true, ...(keepId ? { NOT: { id: keepId } } : {}) },
    data: { isCollectionAgent: false },
  });
}
