import { Prisma } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { accountCode, accountTypeFor, isAccountCode } from '../../common/codes';
import { router, withPermission } from '../trpc';

/*
 * The chart of accounts: the office's ERP chart, and the ledger's accounts —
 * one list. A charge posts to the account it names; a landlord's and a tenant's
 * account are named from it for the ERP import. The ERP's own export (ACC_NO,
 * Description) is imported as it stands, and imported again when the ERP grows.
 *
 * The few accounts the system posts to by itself carry a role (ledger/
 * system-accounts.ts). Their code and name are the office's to change; their
 * type, and whether they exist, are not.
 *
 * The office's bank accounts are marked (isBank): each collection account posts
 * to one of them (ledger/bank-accounts.ts). A bank account is an asset, is no
 * charge's account, and stays one while a collection account posts to it; the
 * Bank role's account always is one.
 */

const accountType = z.enum(['ASSET', 'LIABILITY', 'EQUITY', 'INCOME', 'EXPENSE']);
const name = z.string().trim().min(1).max(191);

/** The rules a bank account keeps, on the account as it will be saved. */
function assertBankAccount(account: { isBank: boolean; type: string; role: string | null; chargeTypes: number }): void {
  if (!account.isBank) return;
  if (account.type !== 'ASSET') throw new TRPCError({ code: 'BAD_REQUEST', message: 'A bank account must be an asset account' });
  if (account.role && account.role !== 'BANK') throw new TRPCError({ code: 'BAD_REQUEST', message: 'A system account cannot be a bank account' });
  if (account.chargeTypes > 0) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: "This account is a charge's account, so it cannot be a bank account" });
  }
}

/** A unique-index clash on the code, as the sentence the office reads. */
function duplicateCode(err: unknown, code: string): never {
  if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
    throw new TRPCError({ code: 'CONFLICT', message: `An account with code ${code} already exists` });
  }
  throw err;
}

export const chartOfAccountsRouter = router({
  /** Every account, with what posts to it and what names it. */
  list: withPermission('gl-account.read').query(async ({ ctx }) => {
    const organizationId = ctx.organizationId ?? '';
    const [accounts, posted] = await Promise.all([
      ctx.prisma.glAccount.findMany({
        where: { organizationId },
        orderBy: { code: 'asc' },
        include: { _count: { select: { chargeTypes: true, landlords: true, tenantCodes: true, bankAccounts: true } } },
      }),
      ctx.prisma.journalLine.groupBy({ by: ['accountId'], where: { account: { organizationId } }, _count: { _all: true } }),
    ]);
    const postings = new Map(posted.map((p) => [p.accountId, p._count._all]));
    return accounts.map((a) => ({
      id: a.id,
      code: a.code,
      name: a.name,
      type: a.type,
      role: a.role,
      isBank: a.isBank,
      isActive: a.isActive,
      postings: postings.get(a.id) ?? 0,
      chargeTypes: a._count.chargeTypes,
      landlords: a._count.landlords,
      tenantCodes: a._count.tenantCodes,
      /** Collection accounts posting here. */
      bankAccounts: a._count.bankAccounts,
    }));
  }),

  /** What a picker offers. Inactive ones are included so a form can still show
   *  the account a record already has; the picker offers only active ones. */
  options: withPermission('gl-account.read').query(({ ctx }) =>
    ctx.prisma.glAccount.findMany({
      where: { organizationId: ctx.organizationId ?? '' },
      orderBy: { code: 'asc' },
      select: { id: true, code: true, name: true, type: true, role: true, isBank: true, isActive: true },
    }),
  ),

  create: withPermission('gl-account.create')
    .input(z.object({ code: z.string(), name, type: accountType.optional(), isBank: z.boolean().default(false) }))
    .mutation(async ({ ctx, input }) => {
      const code = accountCode(input.code);
      if (!code) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Account code must look like 1234-56-7890' });
      const type = input.type ?? accountTypeFor(code);
      assertBankAccount({ isBank: input.isBank, type, role: null, chargeTypes: 0 });
      const row = await ctx.prisma.glAccount
        .create({ data: { organizationId: ctx.organizationId ?? '', code, name: input.name, type, isBank: input.isBank } })
        .catch((err) => duplicateCode(err, code));
      return { id: row.id };
    }),

  /** A code change keeps the account and everything posted to it — it is how
   *  an account takes the code it has in the ERP. */
  update: withPermission('gl-account.update')
    .input(
      z.object({
        id: z.string().min(1),
        code: z.string().optional(),
        name: name.optional(),
        type: accountType.optional(),
        isActive: z.boolean().optional(),
        isBank: z.boolean().optional(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const current = await ctx.prisma.glAccount.findFirst({
        where: { id: input.id, organizationId },
        include: { _count: { select: { chargeTypes: true, bankAccounts: true } } },
      });
      if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Account not found' });
      if (input.isBank === false && current.isBank) {
        if (current.role === 'BANK') throw new TRPCError({ code: 'BAD_REQUEST', message: 'The system Bank account is always a bank account' });
        if (current._count.bankAccounts > 0) {
          throw new TRPCError({ code: 'BAD_REQUEST', message: 'A collection account posts to this account; give it another account first' });
        }
      }
      assertBankAccount({
        isBank: input.isBank ?? current.isBank,
        type: input.type ?? current.type,
        role: current.role,
        chargeTypes: current._count.chargeTypes,
      });
      if (current.role && input.type !== undefined && input.type !== current.type) {
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'The type of a system account cannot be changed' });
      }
      if (current.role && input.isActive === false) {
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'A system account cannot be deactivated or deleted' });
      }
      // An unchanged code is left as it is, so an account still on an older
      // code can be renamed without being made to take a new one.
      const code = input.code === undefined || input.code.trim() === current.code ? undefined : accountCode(input.code);
      if (code === null) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Account code must look like 1234-56-7890' });
      await ctx.prisma.glAccount
        .update({ where: { id: current.id }, data: { code, name: input.name, type: input.type, isActive: input.isActive, isBank: input.isBank } })
        .catch((err) => duplicateCode(err, code ?? current.code));
      return { ok: true };
    }),

  /** Only an account nothing has touched: once posted to or named, it is
   *  history, and is deactivated instead. */
  remove: withPermission('gl-account.delete')
    .input(z.object({ id: z.string().min(1) }))
    .mutation(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const account = await ctx.prisma.glAccount.findFirst({
        where: { id: input.id, organizationId },
        include: { _count: { select: { journalLines: true, chargeTypes: true, landlords: true, tenantCodes: true, bankAccounts: true } } },
      });
      if (!account) throw new TRPCError({ code: 'NOT_FOUND', message: 'Account not found' });
      if (account.role) throw new TRPCError({ code: 'BAD_REQUEST', message: 'A system account cannot be deactivated or deleted' });
      const used = Object.values(account._count).some((n) => n > 0);
      if (used) throw new TRPCError({ code: 'CONFLICT', message: 'This account has postings or is in use, so it cannot be deleted; deactivate it instead' });
      await ctx.prisma.glAccount.delete({ where: { id: account.id } });
      return { ok: true };
    }),

  /**
   * The ERP's export, as rows of code and description. A code the chart lacks
   * is added, typed by the ERP's numbering; one it has takes the ERP's
   * description; nothing is removed, and an account's type, role and status
   * are left as the office set them. A row that cannot be an account is
   * reported, not fatal, so one bad line never holds up the rest.
   */
  import: withPermission('gl-account.create')
    .input(z.object({ rows: z.array(z.object({ code: z.string(), name: z.string() })).max(20000) }))
    .mutation(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const skipped: { code: string; reason: 'format' | 'name' | 'duplicate' }[] = [];
      const rows = new Map<string, string>();
      for (const r of input.rows) {
        const code = r.code.trim();
        const desc = r.name.trim();
        if (code === '' && desc === '') continue;
        if (!isAccountCode(code)) skipped.push({ code, reason: 'format' });
        else if (desc === '' || desc.length > 191) skipped.push({ code, reason: 'name' });
        else if (rows.has(code)) skipped.push({ code, reason: 'duplicate' });
        else rows.set(code, desc);
      }
      const existing = await ctx.prisma.glAccount.findMany({ where: { organizationId }, select: { id: true, code: true, name: true } });
      const byCode = new Map(existing.map((a) => [a.code, a]));
      const renamed = [...rows].filter(([code, desc]) => byCode.has(code) && byCode.get(code)!.name !== desc);
      const added = [...rows].filter(([code]) => !byCode.has(code));
      await ctx.prisma.$transaction([
        ctx.prisma.glAccount.createMany({ data: added.map(([code, desc]) => ({ organizationId, code, name: desc, type: accountTypeFor(code) })) }),
        ...renamed.map(([code, desc]) => ctx.prisma.glAccount.update({ where: { id: byCode.get(code)!.id }, data: { name: desc } })),
      ]);
      return { created: added.length, updated: renamed.length, unchanged: rows.size - added.length - renamed.length, skipped };
    }),
});
