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

const category = z.enum(['RECURRING', 'ONE_OFF', 'DEPOSIT', 'UTILITY', 'ADJUSTMENT']);
type ChargeCategory = z.infer<typeof category>;

const baseInput = z.object({
  code: z
    .string()
    .min(1)
    .max(32)
    .regex(/^[A-Z0-9_]+$/, 'Use uppercase letters, digits and underscores'),
  nameEn: z.string().min(1),
  nameZh: z.string().nullish(),
  category,
  /** The account it posts to, from the chart of accounts — which is also its
   *  ERP code. See chargeAccount for the accounts a charge may name. */
  glAccountId: z.string().nullish(),
  /** Whether a lease's rent-free window frees this charge. Seeded true for RENT
   *  only — the office moves that line here, not in code. Never for a UTILITY
   *  type; see assertWaiverFitsCategory. */
  waivedDuringRentFree: z.boolean().optional(),
  isActive: z.boolean().optional(),
  sortOrder: z.number().int().optional(),
});

/** A rent-free period frees the rent; it never frees usage. A water, electricity
 *  or gas charge is raised from a meter reading by billing's metered path
 *  (billing.service utilityLinesForPeriod), which reads a dial and a tariff and
 *  has no notion of a lease's rent-free window — only expandChargeRules does, and
 *  a metered line never comes from there. A tick here on a UTILITY type was
 *  therefore a promise nothing could keep, and the lease form printed that
 *  promise back at the office ("waives Rent · Electricity").
 *
 *  Refused at the one door that can set it, so the flag and the category can
 *  never disagree — which is also why the engine does not re-check it. Both
 *  halves of the pair are checked together, because switching a flagged type's
 *  CATEGORY to UTILITY arrives at the same forbidden row from the other side. */
function assertWaiverFitsCategory(category: ChargeCategory, waived: boolean): void {
  if (category === 'UTILITY' && waived) {
    throw new TRPCError({
      code: 'BAD_REQUEST',
      message: 'A utility charge is billed on what the meter says was used, so a rent-free period cannot waive it',
    });
  }
}

/** Where a charge may post. A DEPOSIT charge posts to the security deposits
 *  account and nowhere else — the deposit its payment raises reads its balance
 *  there — so it is given that account rather than choosing one. No other
 *  charge may post onto one of the system's own accounts: rent credited to
 *  receivables or to tenant credit would quietly corrupt the balances the
 *  system reads from them. */
async function chargeAccount(
  db: Pick<Prisma.TransactionClient, 'glAccount'>,
  organizationId: string,
  category: ChargeCategory,
  picked: string | null | undefined,
  keep: string | null,
): Promise<string | null> {
  if (category === 'DEPOSIT') {
    const held = await systemAccount(db, organizationId, 'DEPOSITS_HELD');
    if (picked && picked !== held.id) {
      throw new TRPCError({ code: 'BAD_REQUEST', message: `A deposit charge posts to the security deposits account (${held.code})` });
    }
    return held.id;
  }
  const id = (await pickedAccount(db, organizationId, picked, keep)) ?? null;
  const account = id ? await db.glAccount.findUnique({ where: { id }, select: { role: true, isBank: true } }) : null;
  if (account?.role) throw new TRPCError({ code: 'BAD_REQUEST', message: "A system account cannot be a charge's account" });
  // Money in a bank account is a receipt's to post, never a charge's.
  if (account?.isBank) throw new TRPCError({ code: 'BAD_REQUEST', message: "A bank account cannot be a charge's account" });
  return id;
}

export const chargeTypesRouter = router({
  list: withPermission('charge-type.read').query(({ ctx }) =>
    ctx.prisma.chargeType.findMany({
      where: { organizationId: ctx.organizationId ?? undefined },
      orderBy: { sortOrder: 'asc' },
      include: { glAccount: { select: { code: true, name: true } } },
    }),
  ),

  create: withPermission('charge-type.create')
    .input(baseInput)
    .mutation(async ({ ctx, input }) => {
      assertWaiverFitsCategory(input.category, input.waivedDuringRentFree ?? false);
      const glAccountId = await chargeAccount(ctx.prisma, ctx.organizationId ?? '', input.category, input.glAccountId, null);
      return ctx.prisma.chargeType.create({
        data: {
          organizationId: ctx.organizationId ?? '',
          code: input.code,
          nameEn: input.nameEn,
          nameZh: input.nameZh ?? null,
          category: input.category,
          glAccountId,
          waivedDuringRentFree: input.waivedDuringRentFree ?? false,
          isActive: input.isActive ?? true,
          sortOrder: input.sortOrder ?? 0,
        },
      });
    }),

  /** The code is NOT editable. Two features find their charge type by code —
   *  billing looks up LATE_INTEREST to accrue interest, maintenance looks up RM
   *  to bill a repair — and both fail quietly when the row is renamed: interest
   *  simply stops accruing, with no error anywhere. Everything else about a
   *  charge type can be changed. */
  update: withPermission('charge-type.update')
    .input(baseInput.omit({ code: true }).partial().extend({ id: z.string().min(1) }))
    .mutation(async ({ ctx, input }) => {
      const { id, ...data } = input;
      // A partial input: either half of the forbidden pair can already be on the
      // row, so the check is against what the row will BE, not against what this
      // call happens to mention.
      const current = await ctx.prisma.chargeType.findFirst({
        where: { id, organizationId: ctx.organizationId ?? undefined },
        select: { category: true, waivedDuringRentFree: true, glAccountId: true },
      });
      if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Charge type not found' });
      assertWaiverFitsCategory(data.category ?? current.category, data.waivedDuringRentFree ?? current.waivedDuringRentFree);
      // The account as well, for the same reason: a change of category alone
      // can leave the account it names wrong. A deposit charge is given its
      // account, so one made a deposit charge moves there unless told otherwise.
      const category = data.category ?? current.category;
      data.glAccountId = await chargeAccount(
        ctx.prisma,
        ctx.organizationId ?? '',
        category,
        data.glAccountId !== undefined || category === 'DEPOSIT' ? data.glAccountId : current.glAccountId,
        current.glAccountId,
      );
      // Scoped by org and count-checked, like every other write here.
      const claimed = await ctx.prisma.chargeType.updateMany({
        where: { id, organizationId: ctx.organizationId ?? undefined },
        data,
      });
      if (claimed.count !== 1) throw new TRPCError({ code: 'NOT_FOUND', message: 'Charge type not found' });
      return { ok: true };
    }),

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