import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { tenantCode, tenantCodeStem } from '../../common/codes';
import { pickedAccount } from '../../ledger/chart-of-accounts';
import type { Context } from '../trpc';
import { router, withPermission } from '../trpc';

/** A tenant's code in one landlord company's books — see the TenantCode model. */
const codeInput = z.object({ landlordId: z.string().min(1), code: z.string(), glAccountId: z.string().nullish() });

/** Checks a tenant's codes as a set, before anything is written: each names a
 *  landlord of this organisation, at most one per landlord, shaped as
 *  common/codes.ts says and starting with that landlord's code, and not already
 *  someone else's. Checked rather than left to the unique index so the office
 *  is told which code clashes, not handed a constraint name. */
async function checkedCodes(
  db: Context['prisma'],
  organizationId: string,
  tenantId: string | null,
  rows: readonly z.infer<typeof codeInput>[],
) {
  const landlords = await db.landlord.findMany({
    where: { organizationId, id: { in: rows.map((r) => r.landlordId) } },
    select: { id: true, code: true },
  });
  const byId = new Map(landlords.map((l) => [l.id, l]));
  // The account each code already names may since have been retired; it stays.
  const had = new Map(
    tenantId
      ? (await db.tenantCode.findMany({ where: { tenantId }, select: { landlordId: true, glAccountId: true } })).map((c) => [c.landlordId, c.glAccountId])
      : [],
  );
  const seen = new Set<string>();
  const out: { landlordId: string; code: string; glAccountId: string | null }[] = [];
  for (const r of rows) {
    const landlord = byId.get(r.landlordId);
    if (!landlord) throw new TRPCError({ code: 'NOT_FOUND', message: 'Landlord not found' });
    if (seen.has(landlord.id)) throw new TRPCError({ code: 'BAD_REQUEST', message: 'A tenant can have only one code per landlord' });
    seen.add(landlord.id);
    const glAccountId = (await pickedAccount(db, organizationId, r.glAccountId ?? null, had.get(landlord.id))) ?? null;
    out.push({ landlordId: landlord.id, code: tenantCode(r.code, landlord.code), glAccountId });
  }
  const taken = out.length
    ? await db.tenantCode.findFirst({
        where: { organizationId, code: { in: out.map((o) => o.code) }, ...(tenantId ? { NOT: { tenantId } } : {}) },
        select: { code: true },
      })
    : null;
  if (taken) throw new TRPCError({ code: 'CONFLICT', message: `Tenant code ${taken.code} is already in use` });
  return out;
}

export const tenantsRouter = router({
  list: withPermission('tenant.read')
    .input(z.object({ includeArchived: z.boolean().optional() }).optional())
    .query(async ({ ctx, input }) => {
      const rows = await ctx.prisma.tenant.findMany({
        where: {
          organizationId: ctx.organizationId ?? undefined,
          ...(input?.includeArchived ? {} : { deletedAt: null }),
        },
        orderBy: { name: 'asc' },
        include: {
          _count: { select: { leases: { where: { deletedAt: null } } } },
          codes: { orderBy: { code: 'asc' }, select: { landlordId: true, code: true, glAccountId: true, glAccount: { select: { code: true, name: true } }, landlord: { select: { code: true } } } },
        },
      });
      return rows.map((t) => ({
        id: t.id,
        name: t.name,
        nameZh: t.nameZh,
        attention: t.attention,
        email: t.email,
        phone: t.phone,
        address: t.address,
        printAddress: t.printAddress,
        printPhone: t.printPhone,
        printEmail: t.printEmail,
        leases: t._count.leases,
        archived: t.deletedAt != null,
        codes: t.codes.map((c) => ({ landlordId: c.landlordId, landlordCode: c.landlord.code, code: c.code, glAccountId: c.glAccountId, account: c.glAccount })),
      }));
    }),

  /** What a new code for this tenant under this landlord would be: the
   *  landlord's code, the first four letters or digits of the name, and the next
   *  two-digit number after any already taken with that start. Null code when
   *  the name gives fewer than four (a Chinese-only name gives none) or the 99
   *  are used up — the stem is still returned for the office to finish. */
  suggestCode: withPermission('tenant.read')
    .input(z.object({ landlordId: z.string().min(1), name: z.string() }))
    .query(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const landlord = await ctx.prisma.landlord.findFirst({ where: { id: input.landlordId, organizationId }, select: { code: true } });
      if (!landlord) throw new TRPCError({ code: 'NOT_FOUND', message: 'Landlord not found' });
      const stem = tenantCodeStem(landlord.code, input.name);
      if (stem.length < 6) return { stem, code: null };
      const used = await ctx.prisma.tenantCode.findMany({ where: { organizationId, code: { startsWith: stem } }, select: { code: true } });
      const highest = Math.max(0, ...used.map((u) => Number(u.code.slice(6))).filter(Number.isInteger));
      return { stem, code: highest < 99 ? stem + String(highest + 1).padStart(2, '0') : null };
    }),

  create: withPermission('tenant.create')
    .input(
      z.object({
        name: z.string().min(1),
        nameZh: z.string().optional(),
        attention: z.string().optional(),
        email: z.string().email().optional().or(z.literal('')),
        phone: z.string().optional(),
        address: z.string().max(500).optional(),
        /** Whether each is printed on the debit note. Left out, unchanged (new: printed). */
        printAddress: z.boolean().optional(),
        printPhone: z.boolean().optional(),
        printEmail: z.boolean().optional(),
        codes: z.array(codeInput).optional(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const codes = await checkedCodes(ctx.prisma, organizationId, null, input.codes ?? []);
      const t = await ctx.prisma.tenant.create({
        data: {
          organizationId,
          name: input.name,
          nameZh: input.nameZh || null,
          attention: input.attention || null,
          email: input.email || null,
          phone: input.phone || null,
          address: input.address?.trim() || null,
          printAddress: input.printAddress,
          printPhone: input.printPhone,
          printEmail: input.printEmail,
          codes: { create: codes.map((c) => ({ ...c, organizationId })) },
        },
      });
      return { id: t.id };
    }),

  update: withPermission('tenant.update')
    .input(
      z.object({
        id: z.string(),
        name: z.string().min(1),
        nameZh: z.string().optional(),
        attention: z.string().optional(),
        email: z.string().email().optional().or(z.literal('')),
        phone: z.string().optional(),
        address: z.string().max(500).optional(),
        /** Whether each is printed on the debit note. Left out, unchanged (new: printed). */
        printAddress: z.boolean().optional(),
        printPhone: z.boolean().optional(),
        printEmail: z.boolean().optional(),
        /** The whole set when given — replaces what is there. Left out, the
         *  codes are not touched. */
        codes: z.array(codeInput).optional(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const codes = input.codes && (await checkedCodes(ctx.prisma, organizationId, input.id, input.codes));
      await ctx.prisma.$transaction(async (tx) => {
        const res = await tx.tenant.updateMany({
          where: { id: input.id, organizationId, deletedAt: null },
          data: {
            name: input.name,
            nameZh: input.nameZh || null,
            attention: input.attention || null,
            email: input.email || null,
            phone: input.phone || null,
            address: input.address?.trim() || null,
            printAddress: input.printAddress,
            printPhone: input.printPhone,
            printEmail: input.printEmail,
          },
        });
        if (res.count !== 1) throw new TRPCError({ code: 'NOT_FOUND' });
        if (codes) {
          await tx.tenantCode.deleteMany({ where: { tenantId: input.id } });
          await tx.tenantCode.createMany({ data: codes.map((c) => ({ ...c, organizationId, tenantId: input.id })) });
        }
      });
      return { id: input.id };
    }),

  /** Soft-delete (archive). Blocked while the tenant still has live leases or
   * unsettled deposits, so no financial history is orphaned. Reversible. */
  archive: withPermission('tenant.delete')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? undefined;
      const leases = await ctx.prisma.lease.count({ where: { tenantId: input.id, organizationId: org, deletedAt: null } });
      if (leases > 0) {
        throw new TRPCError({ code: 'CONFLICT', message: `This tenant still has ${leases} lease(s); archive or reassign them first.` });
      }
      const openDeposits = await ctx.prisma.deposit.count({
        where: { tenantId: input.id, organizationId: org, status: { in: ['HELD', 'PARTIALLY_APPLIED'] } },
      });
      if (openDeposits > 0) {
        throw new TRPCError({ code: 'CONFLICT', message: `This tenant still has ${openDeposits} unsettled deposit(s); settle them first.` });
      }
      const res = await ctx.prisma.tenant.updateMany({
        where: { id: input.id, organizationId: org, deletedAt: null },
        data: { deletedAt: new Date() },
      });
      if (res.count !== 1) throw new TRPCError({ code: 'NOT_FOUND' });
      return { id: input.id };
    }),

  restore: withPermission('tenant.delete')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const res = await ctx.prisma.tenant.updateMany({
        where: { id: input.id, organizationId: ctx.organizationId ?? undefined, deletedAt: { not: null } },
        data: { deletedAt: null },
      });
      if (res.count !== 1) throw new TRPCError({ code: 'NOT_FOUND' });
      return { id: input.id };
    }),
});
