import type { PrismaClient } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { findReferenceValue, referenceOptions } from '../reference-lookup';
import { router, withPermission } from '../trpc';
import { landlordCode } from '../../common/codes';
import { pickedAccount } from '../../ledger/chart-of-accounts';

/**
 * The companies the group owns its buildings through. The system runs as one
 * Organization — that does not change — but a building belongs to one of ~20
 * limited companies, and which one decides whose letterhead a debit note will
 * eventually carry.
 *
 * Two ways out of circulation, as elsewhere in this schema: deactivating stops
 * a company being offered on new properties while leaving it readable on the
 * ones that already name it (BankAccount's switch), and archiving hides it
 * altogether but only once it owns nothing (Property's soft delete). Neither
 * ever destroys the row — a property that pointed here is history.
 */
const landlordInput = z.object({
  code: z.string().min(1).max(16),
  name: z.string().min(1).max(160),
  nameZh: z.string().max(160).optional().nullable(),
  /** This company's account, from the chart of accounts, for the ERP import.
   *  Nothing posts to it — see the schema comment. */
  glAccountId: z.string().optional().nullable(),
  address: z.string().max(255).optional().nullable(),
  tel: z.string().max(40).optional().nullable(),
  email: z.string().max(120).optional().nullable(),
  /** Tel / Email for its properties in one country, printed on their
   *  letterhead instead of the company's own (common/letterhead.ts). The whole
   *  set when given; left out, not touched. */
  contacts: z
    .array(z.object({ countryId: z.string(), tel: z.string().max(40).optional().nullable(), email: z.string().max(120).optional().nullable() }))
    .optional(),
  isActive: z.boolean().default(true),
  sortOrder: z.number().int().min(0).default(0),
});

type ContactInput = NonNullable<z.infer<typeof landlordInput>['contacts']>;

/** One contact per country, each country one of this org's own; blank rows go. */
async function checkContacts(prisma: PrismaClient, organizationId: string, contacts: ContactInput) {
  const kept = contacts
    .map((c) => ({ countryId: c.countryId, tel: c.tel?.trim() || null, email: c.email?.trim() || null }))
    .filter((c) => c.tel || c.email);
  if (new Set(kept.map((c) => c.countryId)).size !== kept.length) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'Each country can have only one contact' });
  }
  for (const c of kept) {
    if (!(await findReferenceValue(prisma, organizationId, 'COUNTRY', c.countryId))) {
      throw new TRPCError({ code: 'BAD_REQUEST', message: 'Country not found' });
    }
  }
  return kept;
}

const withContacts = { select: { countryId: true, tel: true, email: true }, orderBy: { countryId: 'asc' } } as const;

type LandlordRow = {
  id: string; code: string; name: string; nameZh: string | null;
  glAccountId: string | null; glAccount: { code: string; name: string } | null;
  address: string | null; tel: string | null; email: string | null;
  contacts: { countryId: string; tel: string | null; email: string | null }[];
  isActive: boolean; sortOrder: number; deletedAt: Date | null;
};

const shape = (l: LandlordRow, properties: number) => ({
  id: l.id,
  code: l.code,
  name: l.name,
  nameZh: l.nameZh,
  glAccountId: l.glAccountId,
  account: l.glAccount,
  address: l.address,
  tel: l.tel,
  email: l.email,
  contacts: l.contacts,
  isActive: l.isActive,
  sortOrder: l.sortOrder,
  properties,
  archived: l.deletedAt != null,
});

export const landlordsRouter = router({
  list: withPermission('landlord.read')
    .input(z.object({ includeArchived: z.boolean().optional() }).optional())
    .query(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? undefined;
      const rows = await ctx.prisma.landlord.findMany({
        where: { organizationId: org, ...(input?.includeArchived ? {} : { deletedAt: null }) },
        orderBy: [{ isActive: 'desc' }, { sortOrder: 'asc' }, { code: 'asc' }],
        // How many properties each owns, so retiring one is an informed choice —
        // and one query, not one per row. Archived buildings are counted: they
        // still name the company, and they are what `archive` below blocks on,
        // so the number on screen has to be the number the guard uses.
        include: { _count: { select: { properties: true } }, glAccount: { select: { code: true, name: true } }, contacts: withContacts },
      });
      return rows.map((l) => shape(l, l._count.properties));
    }),

  get: withPermission('landlord.read')
    .input(z.object({ id: z.string() }))
    .query(async ({ ctx, input }) => {
      const l = await ctx.prisma.landlord.findFirst({
        where: { id: input.id, organizationId: ctx.organizationId ?? undefined },
        include: { _count: { select: { properties: true } }, glAccount: { select: { code: true, name: true } }, contacts: withContacts },
      });
      if (!l) throw new TRPCError({ code: 'NOT_FOUND', message: 'Landlord not found' });
      return shape(l, l._count.properties);
    }),

  /** The countries a contact can be for — the Option Lists screen's own. */
  countries: withPermission('landlord.read').query(({ ctx }) => referenceOptions(ctx.prisma, ctx.organizationId ?? undefined, 'COUNTRY')),

  create: withPermission('landlord.create')
    .input(landlordInput)
    .mutation(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const { code, contacts, ...rest } = input;
      const upper = landlordCode(code);
      // Checked rather than left to the unique index, so the caller gets a
      // sentence instead of a raw Prisma constraint message. Archived rows count:
      // the index does not care that one is hidden.
      const dup = await ctx.prisma.landlord.findFirst({ where: { organizationId, code: upper }, select: { id: true } });
      if (dup) throw new TRPCError({ code: 'CONFLICT', message: 'A landlord with that code already exists' });
      const glAccountId = await pickedAccount(ctx.prisma, organizationId, rest.glAccountId);
      const local = await checkContacts(ctx.prisma, organizationId, contacts ?? []);
      const row = await ctx.prisma.landlord.create({ data: { ...rest, glAccountId, code: upper, organizationId, contacts: { create: local } } });
      return { id: row.id };
    }),

  update: withPermission('landlord.update')
    .input(landlordInput.extend({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const { id, code, contacts, ...rest } = input;
      const existing = await ctx.prisma.landlord.findFirst({ where: { id, organizationId }, select: { id: true, glAccountId: true } });
      if (!existing) throw new TRPCError({ code: 'NOT_FOUND', message: 'Landlord not found' });
      const upper = landlordCode(code);
      const dup = await ctx.prisma.landlord.findFirst({
        where: { organizationId, code: upper, NOT: { id } },
        select: { id: true },
      });
      if (dup) throw new TRPCError({ code: 'CONFLICT', message: 'A landlord with that code already exists' });
      if (!rest.address?.trim()) {
        // The other way into a letterhead with no address: the property was
        // pointed here while the address was on file, and the address is being
        // taken away now. Refused, because the next debit note printed for those
        // buildings would carry a company name and nothing else.
        // Archived buildings count, for the reason `archive` states below:
        // restore one and it is live again, still printing under this company.
        // Skipping them would let a building be archived, the address cleared,
        // the building restored — and the note would then silently print the
        // management company while the Properties list still names this one.
        const printing = await ctx.prisma.property.count({
          where: { organizationId, landlordId: id, letterheadSource: 'LANDLORD' },
        });
        if (printing > 0) {
          throw new TRPCError({
            code: 'CONFLICT',
            message: `${printing} property(ies) print their debit notes under this company, so it needs an address`,
          });
        }
      }
      const glAccountId = await pickedAccount(ctx.prisma, organizationId, rest.glAccountId, existing.glAccountId);
      const local = contacts && (await checkContacts(ctx.prisma, organizationId, contacts));
      await ctx.prisma.landlord.update({
        where: { id },
        // Replaced whole: the form sends the full list, and a row it dropped is one taken away.
        data: { ...rest, glAccountId, code: upper, ...(local ? { contacts: { deleteMany: {}, create: local } } : {}) },
      });
      return { ok: true };
    }),

  /** Takes it out of the pickers without hiding it: a property that already
   *  names it keeps resolving, exactly as a deactivated bank account does. */
  setActive: withPermission('landlord.update')
    .input(z.object({ id: z.string(), isActive: z.boolean() }))
    .mutation(async ({ ctx, input }) => {
      const claimed = await ctx.prisma.landlord.updateMany({
        where: { id: input.id, organizationId: ctx.organizationId ?? undefined, deletedAt: null },
        data: { isActive: input.isActive },
      });
      if (claimed.count !== 1) throw new TRPCError({ code: 'NOT_FOUND', message: 'Landlord not found' });
      return { ok: true };
    }),

  /** Soft-delete (archive). Blocked while it still owns a property, so no
   *  building is left pointing at an owner nobody can see. Reversible. */
  archive: withPermission('landlord.delete')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? undefined;
      // Archived buildings count. Archiving one is not letting go of it: restore
      // it and it is live again, still naming this company — a company the
      // pickers no longer offer and the default list no longer shows.
      const properties = await ctx.prisma.property.count({
        where: { landlordId: input.id, organizationId: org },
      });
      if (properties > 0) {
        throw new TRPCError({ code: 'CONFLICT', message: `This landlord still owns ${properties} property(ies); reassign them first.` });
      }
      const res = await ctx.prisma.landlord.updateMany({
        where: { id: input.id, organizationId: org, deletedAt: null },
        data: { deletedAt: new Date() },
      });
      if (res.count !== 1) throw new TRPCError({ code: 'NOT_FOUND', message: 'Landlord not found' });
      return { id: input.id };
    }),

  restore: withPermission('landlord.delete')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const res = await ctx.prisma.landlord.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', message: 'Landlord not found' });
      return { id: input.id };
    }),
});
