import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { router, withPermission } from '../trpc';

/**
 * The lookup lists the office maintains itself — the maintenance taxonomy a
 * repair is filed under, the category a property is, and the type and use a
 * tenancy is let on. The seed comment has always claimed these are
 * "user-configurable, not hardcoded (replaces the legacy's numeric-string
 * priority/category baked into PHP controllers)". They were exactly as
 * hardcoded, only in TypeScript.
 *
 * This list was once the two maintenance domains, because a search across the
 * API and both front ends found no reader for any of the others — an editor for
 * those would have been a screen for data nothing consumes. That stopped being
 * true when the property gained a category and the lease gained a type and a
 * use: all three are now written and read, so all three are editable here — and
 * so is what a letter to a property was about, which the notice log writes, and
 * what kind of document is filed against a building, which its document store
 * writes — and the country a property is in, which picks its landlord's contact
 * for the letterhead. REGION, AMENITY and MANAGEMENT_TYPE stay out for the original reason.
 *
 * No delete. A record filed months ago still points at its value, and the name
 * lookups resolve by id without filtering on isActive, so a retired value keeps
 * reading correctly on everything that used it. Deleting would blank the
 * category on historical records instead.
 */
const EDITABLE_DOMAINS = [
  'MAINTENANCE_CATEGORY',
  'MAINTENANCE_PRIORITY',
  'PROPERTY_CATEGORY',
  'LEASE_TYPE',
  'LEASE_USAGE',
  'NOTICE_TYPE',
  'PROPERTY_DOCUMENT_TYPE',
  'MAINTENANCE_DOCUMENT_TYPE',
  'COUNTRY',
] as const;
const domain = z.enum(EDITABLE_DOMAINS);

const valueInput = z.object({
  nameEn: z.string().min(1).max(80),
  nameZh: z.string().max(80).optional().nullable(),
  sortOrder: z.number().int().min(0).default(0),
  isActive: z.boolean().default(true),
});

export const referenceValuesRouter = router({
  list: withPermission('reference-value.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.referenceValue.findMany({
      where: { organizationId: ctx.organizationId ?? undefined, domain: { in: [...EDITABLE_DOMAINS] } },
      orderBy: [{ domain: 'asc' }, { isActive: 'desc' }, { sortOrder: 'asc' }, { nameEn: 'asc' }],
    });
    // How many records already refer to each, so retiring one is an informed
    // choice. EVERY editable list is counted, or the number lies by omission on
    // the ones that are not maintenance.
    const org = ctx.organizationId ?? undefined;
    const [byCategory, byPriority, byPropertyCategory, byLeaseType, byUsage, byNoticeType, byDocumentType, byCountry, byContactCountry] = await Promise.all([
      ctx.prisma.maintenanceRequest.groupBy({ by: ['categoryId'], where: { organizationId: org, categoryId: { not: null } }, _count: { _all: true } }),
      ctx.prisma.maintenanceRequest.groupBy({ by: ['priorityId'], where: { organizationId: org, priorityId: { not: null } }, _count: { _all: true } }),
      ctx.prisma.property.groupBy({ by: ['categoryId'], where: { organizationId: org, deletedAt: null, categoryId: { not: null } }, _count: { _all: true } }),
      ctx.prisma.lease.groupBy({ by: ['leaseTypeId'], where: { organizationId: org, deletedAt: null, leaseTypeId: { not: null } }, _count: { _all: true } }),
      ctx.prisma.lease.groupBy({ by: ['usageId'], where: { organizationId: org, deletedAt: null, usageId: { not: null } }, _count: { _all: true } }),
      ctx.prisma.propertyNotice.groupBy({ by: ['typeId'], where: { organizationId: org }, _count: { _all: true } }),
      // Both classified owners: a building's paperwork and a repair's proof.
      ctx.prisma.attachment.groupBy({
        by: ['documentTypeId'],
        where: { organizationId: org, ownerType: { in: ['PROPERTY', 'MAINTENANCE_REQUEST'] }, documentTypeId: { not: null } },
        _count: { _all: true },
      }),
      // A country is where a property is, and what a landlord's local contact is for.
      ctx.prisma.property.groupBy({ by: ['countryId'], where: { organizationId: org, deletedAt: null, countryId: { not: null } }, _count: { _all: true } }),
      ctx.prisma.landlordContact.groupBy({ by: ['countryId'], where: { landlord: { organizationId: org } }, _count: { _all: true } }),
    ]);
    const used = new Map<string, number>();
    const tally = (id: string | null, n: number): void => { if (id) used.set(id, (used.get(id) ?? 0) + n); };
    for (const c of byCategory) tally(c.categoryId, c._count._all);
    for (const p of byPriority) tally(p.priorityId, p._count._all);
    for (const p of byPropertyCategory) tally(p.categoryId, p._count._all);
    for (const t of byLeaseType) tally(t.leaseTypeId, t._count._all);
    for (const u of byUsage) tally(u.usageId, u._count._all);
    for (const n of byNoticeType) tally(n.typeId, n._count._all);
    for (const d of byDocumentType) tally(d.documentTypeId, d._count._all);
    for (const p of byCountry) tally(p.countryId, p._count._all);
    for (const c of byContactCountry) tally(c.countryId, c._count._all);
    return rows.map((r) => ({
      id: r.id,
      // Narrowed: the query filters to the editable lists, so the client should
      // not have to handle domains it will never receive.
      domain: r.domain as (typeof EDITABLE_DOMAINS)[number],
      code: r.code,
      nameEn: r.nameEn,
      nameZh: r.nameZh,
      sortOrder: r.sortOrder,
      isActive: r.isActive,
      usageCount: used.get(r.id) ?? 0,
    }));
  }),

  create: withPermission('reference-value.create')
    .input(valueInput.extend({ domain, code: z.string().min(1).max(32) }))
    .mutation(async ({ ctx, input }) => {
      const organizationId = ctx.organizationId ?? '';
      const code = input.code.trim().toUpperCase();
      const dup = await ctx.prisma.referenceValue.findFirst({
        where: { organizationId, domain: input.domain, code },
        select: { id: true },
      });
      // Checked rather than left to the composite unique index, so the caller
      // gets a sentence instead of a raw Prisma constraint message.
      if (dup) throw new TRPCError({ code: 'CONFLICT', message: 'A value with that code already exists in this list' });
      const { code: _ignored, ...rest } = input;
      const row = await ctx.prisma.referenceValue.create({ data: { ...rest, code, organizationId } });
      return { id: row.id };
    }),

  /** Neither the code nor the domain is editable: a request already filed refers
   *  to this row, and moving it between lists would silently recategorise it. */
  update: withPermission('reference-value.update')
    .input(valueInput.extend({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const { id, ...data } = input;
      const claimed = await ctx.prisma.referenceValue.updateMany({
        where: { id, organizationId: ctx.organizationId ?? undefined, domain: { in: [...EDITABLE_DOMAINS] } },
        data,
      });
      if (claimed.count !== 1) throw new TRPCError({ code: 'NOT_FOUND', message: 'Reference value not found' });
      return { ok: true };
    }),

  setActive: withPermission('reference-value.update')
    .input(z.object({ id: z.string(), isActive: z.boolean() }))
    .mutation(async ({ ctx, input }) => {
      const claimed = await ctx.prisma.referenceValue.updateMany({
        where: { id: input.id, organizationId: ctx.organizationId ?? undefined, domain: { in: [...EDITABLE_DOMAINS] } },
        data: { isActive: input.isActive },
      });
      if (claimed.count !== 1) throw new TRPCError({ code: 'NOT_FOUND', message: 'Reference value not found' });
      return { ok: true };
    }),
});
