import type { PrismaClient } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { parseDay } from '../../common/hk-date';
import { findReferenceValue, referenceOptions } from '../reference-lookup';
import { router, withPermission } from '../trpc';

/**
 * The notice / letter log: what the office sent about a building and when.
 *
 * The spreadsheet kept this on its own tab — Date | Type | Remark — and the
 * system had nowhere for it, so "subject to change with notice" was a promise
 * nothing could evidence. An entry may name ONE tenancy (the letter went to one
 * tenant) and may name the standard charge it announced, which is what ties the
 * notification to the rate change it gave notice of.
 *
 * Staff only. The tenant portal has no procedure that reads this table, and the
 * attachment service refuses a tenant on a PROPERTY_NOTICE owner outright.
 */

const day = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Pick a date');

const noticeFields = z.object({
  propertyId: z.string(),
  date: day,
  typeId: z.string().min(1),
  remark: z.string().min(1).max(5000),
  /** Set when the letter went to one tenancy rather than the whole building. */
  leaseId: z.string().optional().nullable(),
  /** The rate change it announced, when it announced one. */
  standardChargeId: z.string().optional().nullable(),
});

/** Everything an entry points at has to belong to this org AND to the property
 *  named on the entry — otherwise a letter about one building could quietly
 *  reference another building's tenancy or fee. */
async function checkLinks(
  prisma: PrismaClient,
  organizationId: string,
  input: { propertyId: string; typeId: string; leaseId?: string | null; standardChargeId?: string | null },
): Promise<void> {
  const property = await prisma.property.findFirst({ where: { id: input.propertyId, organizationId }, select: { id: true } });
  if (!property) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Property not found' });
  if (!(await findReferenceValue(prisma, organizationId, 'NOTICE_TYPE', input.typeId))) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'Notice type not found' });
  }
  if (input.leaseId) {
    const lease = await prisma.lease.findFirst({
      where: { id: input.leaseId, organizationId, units: { some: { unit: { propertyId: input.propertyId } } } },
      select: { id: true },
    });
    if (!lease) throw new TRPCError({ code: 'BAD_REQUEST', message: 'That lease is not on this property' });
  }
  if (input.standardChargeId) {
    const sc = await prisma.standardCharge.findFirst({
      where: { id: input.standardChargeId, organizationId, propertyId: input.propertyId },
      select: { id: true },
    });
    if (!sc) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Standard charge not found' });
  }
}

const noticeInclude = {
  property: { select: { name: true } },
  lease: { select: { reference: true, tenant: { select: { name: true } } } },
  standardCharge: {
    select: {
      id: true,
      amount: true,
      effectiveFrom: true,
      unit: { select: { name: true } },
      chargeType: { select: { nameEn: true, nameZh: true } },
    },
  },
} as const;

export const noticesRouter = router({
  list: withPermission('notice.read')
    .input(z.object({ propertyId: z.string().optional(), leaseId: z.string().optional() }).optional())
    .query(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? undefined;
      const rows = await ctx.prisma.propertyNotice.findMany({
        where: { organizationId: org, ...(input?.propertyId ? { propertyId: input.propertyId } : {}), ...(input?.leaseId ? { leaseId: input.leaseId } : {}) },
        orderBy: [{ date: 'desc' }, { createdAt: 'desc' }],
        take: 500,
        include: noticeInclude,
      });
      // Types are reference values, not a relation, so one lookup for the page
      // rather than one per row — the same shape properties.list uses.
      const [types, files, users] = await Promise.all([
        ctx.prisma.referenceValue.findMany({ where: { organizationId: org, domain: 'NOTICE_TYPE' }, select: { id: true, nameEn: true, nameZh: true } }),
        rows.length
          ? ctx.prisma.attachment.groupBy({
              by: ['ownerId'],
              where: { organizationId: org, ownerType: 'PROPERTY_NOTICE', ownerId: { in: rows.map((r) => r.id) } },
              _count: { _all: true },
            })
          : Promise.resolve([]),
        ctx.prisma.user.findMany({
          where: { id: { in: [...new Set(rows.map((r) => r.recordedByUserId).filter((v): v is string => !!v))] } },
          select: { id: true, name: true },
        }),
      ]);
      const typeById = new Map(types.map((t) => [t.id, t]));
      const fileCount = new Map(files.map((f) => [f.ownerId, f._count._all]));
      const nameById = new Map(users.map((u) => [u.id, u.name]));
      return rows.map((r) => ({
        id: r.id,
        propertyId: r.propertyId,
        propertyName: r.property.name,
        date: r.date.toISOString().slice(0, 10),
        typeId: r.typeId,
        typeNameEn: typeById.get(r.typeId)?.nameEn ?? null,
        typeNameZh: typeById.get(r.typeId)?.nameZh ?? null,
        remark: r.remark,
        leaseId: r.leaseId,
        leaseReference: r.lease?.reference ?? null,
        tenantName: r.lease?.tenant.name ?? null,
        standardChargeId: r.standardChargeId,
        standardCharge: r.standardCharge
          ? {
              id: r.standardCharge.id,
              amount: r.standardCharge.amount.toFixed(2),
              effectiveFrom: r.standardCharge.effectiveFrom.toISOString().slice(0, 10),
              unitName: r.standardCharge.unit?.name ?? null,
              chargeTypeNameEn: r.standardCharge.chargeType.nameEn,
              chargeTypeNameZh: r.standardCharge.chargeType.nameZh,
            }
          : null,
        attachments: fileCount.get(r.id) ?? 0,
        recordedByName: r.recordedByUserId ? nameById.get(r.recordedByUserId) ?? null : null,
        createdAt: r.createdAt,
      }));
    }),

  get: withPermission('notice.read')
    .input(z.object({ id: z.string() }))
    .query(async ({ ctx, input }) => {
      const r = await ctx.prisma.propertyNotice.findFirst({
        where: { id: input.id, organizationId: ctx.organizationId ?? undefined },
        include: noticeInclude,
      });
      if (!r) throw new TRPCError({ code: 'NOT_FOUND', message: 'Notice not found' });
      const [type, attachments] = await Promise.all([
        // Resolved WITHOUT the isActive filter the picker uses: a type the office
        // has since retired is still this letter's answer.
        ctx.prisma.referenceValue.findFirst({ where: { id: r.typeId, domain: 'NOTICE_TYPE' }, select: { id: true, nameEn: true, nameZh: true } }),
        ctx.prisma.attachment.findMany({
          where: { organizationId: ctx.organizationId ?? undefined, ownerType: 'PROPERTY_NOTICE', ownerId: r.id },
          orderBy: { createdAt: 'asc' },
          select: { id: true, filename: true, mimeType: true, sizeBytes: true, createdAt: true },
        }),
      ]);
      return {
        id: r.id,
        propertyId: r.propertyId,
        propertyName: r.property.name,
        date: r.date.toISOString().slice(0, 10),
        typeId: r.typeId,
        typeNameEn: type?.nameEn ?? null,
        typeNameZh: type?.nameZh ?? null,
        remark: r.remark,
        leaseId: r.leaseId,
        leaseReference: r.lease?.reference ?? null,
        tenantName: r.lease?.tenant.name ?? null,
        standardChargeId: r.standardChargeId,
        standardCharge: r.standardCharge
          ? {
              id: r.standardCharge.id,
              amount: r.standardCharge.amount.toFixed(2),
              effectiveFrom: r.standardCharge.effectiveFrom.toISOString().slice(0, 10),
              unitName: r.standardCharge.unit?.name ?? null,
              chargeTypeNameEn: r.standardCharge.chargeType.nameEn,
              chargeTypeNameZh: r.standardCharge.chargeType.nameZh,
            }
          : null,
        attachments,
        recordedByUserId: r.recordedByUserId,
        createdAt: r.createdAt,
      };
    }),

  /** The pickers the notice form needs. Leases carry their property so the form
   *  can narrow "sent to one tenant" to the building it is filing against. */
  formData: withPermission('notice.read').query(async ({ ctx }) => {
    const org = ctx.organizationId ?? undefined;
    const [properties, types, leases] = await Promise.all([
      ctx.prisma.property.findMany({ where: { organizationId: org, deletedAt: null }, orderBy: [{ name: 'asc' }, { code: 'asc' }], select: { id: true, name: true, code: true } }),
      referenceOptions(ctx.prisma, org, 'NOTICE_TYPE'),
      ctx.prisma.lease.findMany({
        where: { organizationId: org, deletedAt: null, status: { in: ['DRAFT', 'ACTIVE'] } },
        orderBy: { reference: 'asc' },
        select: { id: true, reference: true, tenant: { select: { name: true } }, units: { select: { unit: { select: { propertyId: true } } } } },
      }),
    ]);
    return {
      properties,
      types,
      // A lease can take units from several purchases of its building.
      leases: leases.map((l) => ({ id: l.id, reference: l.reference, propertyIds: [...new Set(l.units.map((u) => u.unit.propertyId))], tenantName: l.tenant.name })),
    };
  }),

  create: withPermission('notice.create')
    .input(noticeFields)
    .mutation(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? '';
      await checkLinks(ctx.prisma, org, input);
      const row = await ctx.prisma.propertyNotice.create({
        data: {
          organizationId: org,
          propertyId: input.propertyId,
          date: parseDay(input.date),
          typeId: input.typeId,
          remark: input.remark,
          leaseId: input.leaseId || null,
          standardChargeId: input.standardChargeId || null,
          recordedByUserId: ctx.user.id,
        },
        select: { id: true },
      });
      return { id: row.id };
    }),

  update: withPermission('notice.update')
    .input(noticeFields.extend({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? '';
      await checkLinks(ctx.prisma, org, input);
      // org-scoped and count-checked, so a caller can't edit another org's row by id.
      const claimed = await ctx.prisma.propertyNotice.updateMany({
        where: { id: input.id, organizationId: org },
        data: {
          propertyId: input.propertyId,
          date: parseDay(input.date),
          typeId: input.typeId,
          remark: input.remark,
          leaseId: input.leaseId || null,
          standardChargeId: input.standardChargeId || null,
        },
      });
      if (claimed.count !== 1) throw new TRPCError({ code: 'NOT_FOUND', message: 'Notice not found' });
      return { ok: true };
    }),

  remove: withPermission('notice.delete')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? '';
      await ctx.prisma.$transaction(async (tx) => {
        const found = await tx.propertyNotice.findFirst({ where: { id: input.id, organizationId: org }, select: { id: true } });
        if (!found) throw new TRPCError({ code: 'NOT_FOUND', message: 'Notice not found' });
        // The attachment rows go with it: a row pointing at a deleted owner is
        // unreachable (every download resolves its owner first) and would never
        // be cleaned up. The files on disk are left to scripts/prune-orphan-
        // uploads.ts, which exists for exactly this.
        await tx.attachment.deleteMany({ where: { organizationId: org, ownerType: 'PROPERTY_NOTICE', ownerId: input.id } });
        await tx.propertyNotice.delete({ where: { id: input.id } });
      });
      return { ok: true };
    }),
});
