import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { hkToday, parseDay } from '../../common/hk-date';
import { propertyLabel } from '../../common/property-label';
import { isInForce } from '../../standard-charges/standard-charge.resolution';
import {
  applyToLeases,
  correctStandardCharge,
  effectiveFigures,
  loadHistory,
  recordStandardCharge,
  removeStandardCharge,
  reviewStandardCharge,
  rulesNotFollowing,
} from '../../standard-charges/standard-charge.service';
import { findReferenceValue } from '../reference-lookup';
import { router, withPermission } from '../trpc';

/**
 * What a recurring charge costs at an address, and the review that follows a
 * change to it.
 *
 * PERMISSIONS: the figures themselves ride on the property — whoever may read a
 * property may read them, whoever may update one may record and correct them.
 * `applyToLeases`, which rewrites a tenancy's own charge rules, needs
 * `lease.update` instead: it changes what a tenant is billed, and that is a
 * lease decision wherever it is started from.
 *
 * Every decision is the service's; this file validates shapes and delegates.
 */

const money = z.string().regex(/^\d+(\.\d{1,2})?$/, 'Enter a valid amount');
const day = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Pick a date');

/** The letter that announced a change, recorded in the same save. Optional, and
 *  the one thing that ties "we notified them on the 3rd" to "the fee went from
 *  500 to 600 on the 1st". */
const noticeInput = z.object({
  date: day,
  typeId: z.string().min(1),
  remark: z.string().min(1).max(5000),
});

export const standardChargesRouter = router({
  /** One property's whole history, plus what each scope actually pays today (or
   *  on `onDate`) after unit-beats-property. */
  list: withPermission('property.read')
    .input(z.object({ propertyId: z.string(), onDate: day.optional() }))
    .query(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? '';
      const property = await ctx.prisma.property.findFirst({
        where: { id: input.propertyId, organizationId: org },
        select: { id: true, name: true, units: { where: { deletedAt: null }, orderBy: { name: 'asc' }, select: { id: true, name: true } } },
      });
      if (!property) throw new TRPCError({ code: 'NOT_FOUND', message: 'Property not found' });
      const onDate = input.onDate ? parseDay(input.onDate) : hkToday();
      const history = await loadHistory(ctx.prisma, org, property.id);

      const typeIds = [...new Set(history.map((h) => h.chargeTypeId))];
      const scopedUnitIds = [...new Set(history.map((h) => h.unitId).filter((v): v is string => !!v))];
      const [types, namedUnits, pickable, users] = await Promise.all([
        typeIds.length
          ? ctx.prisma.chargeType.findMany({ where: { id: { in: typeIds } }, select: { id: true, code: true, nameEn: true, nameZh: true } })
          : Promise.resolve([]),
        // Names for the history, WITHOUT the deletedAt filter the picker uses: a
        // figure recorded against a unit since removed still reads as that
        // unit's, not as the building's.
        scopedUnitIds.length
          ? ctx.prisma.unit.findMany({ where: { id: { in: scopedUnitIds } }, select: { id: true, name: true } })
          : Promise.resolve([]),
        // Only RECURRING types can carry a standard amount, so the picker offers
        // only those — the service refuses the rest anyway.
        ctx.prisma.chargeType.findMany({
          where: { organizationId: org, category: 'RECURRING', isActive: true },
          orderBy: { sortOrder: 'asc' },
          select: { id: true, code: true, nameEn: true, nameZh: true },
        }),
        ctx.prisma.user.findMany({
          where: { id: { in: [...new Set(history.map((h) => h.recordedByUserId).filter((v): v is string => !!v))] } },
          select: { id: true, name: true },
        }),
      ]);
      const typeById = new Map(types.map((t) => [t.id, t]));
      const unitById = new Map(namedUnits.map((u) => [u.id, u]));
      const nameById = new Map(users.map((u) => [u.id, u.name]));

      return {
        property: { id: property.id, name: property.name },
        units: property.units,
        chargeTypes: pickable,
        onDate: onDate.toISOString().slice(0, 10),
        rows: history.map((r) => ({
          id: r.id,
          chargeTypeId: r.chargeTypeId,
          chargeTypeCode: typeById.get(r.chargeTypeId)?.code ?? null,
          chargeTypeNameEn: typeById.get(r.chargeTypeId)?.nameEn ?? null,
          chargeTypeNameZh: typeById.get(r.chargeTypeId)?.nameZh ?? null,
          unitId: r.unitId,
          unitName: r.unitId ? unitById.get(r.unitId)?.name ?? null : null,
          amount: r.amount,
          effectiveFrom: r.effectiveFrom.toISOString().slice(0, 10),
          note: r.note,
          recordedByUserId: r.recordedByUserId,
          recordedByName: r.recordedByUserId ? nameById.get(r.recordedByUserId) ?? null : null,
          createdAt: r.createdAt,
          /** True for the row its own scope is answered by on `onDate`: the
           *  others are either superseded or not due yet. */
          inForce: isInForce(history, r, onDate),
          /** A row dated after `onDate` — announced, not yet charging. */
          future: r.effectiveFrom.getTime() > onDate.getTime(),
        })),
        effective: effectiveFigures(history, property.units.map((u) => u.id), onDate),
      };
    }),

  /** The Management Fee Records page: every property's figures for one charge
   *  — the management fee unless another is picked — newest first, each with its
   *  standing today and the notices that announced it; and, for a reader of
   *  leases, the tenancies charging it at a price of their own. */
  all: withPermission('property.read')
    .input(z.object({ chargeTypeId: z.string().optional() }).optional())
    .query(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? '';
      const today = hkToday();
      const [chargeTypes, properties] = await Promise.all([
        ctx.prisma.chargeType.findMany({
          where: { organizationId: org, category: 'RECURRING', isActive: true },
          orderBy: { sortOrder: 'asc' },
          select: { id: true, code: true, nameEn: true, nameZh: true },
        }),
        ctx.prisma.property.findMany({
          where: { organizationId: org, deletedAt: null },
          orderBy: [{ name: 'asc' }, { code: 'asc' }],
          select: { id: true, name: true, code: true, units: { where: { deletedAt: null }, orderBy: { name: 'asc' }, select: { id: true, name: true } } },
        }),
      ]);
      // The management fee by its seeded code; the office may have renamed it,
      // and then the first recurring charge is shown until one is picked.
      const chargeTypeId = input?.chargeTypeId ?? chargeTypes.find((c) => c.code === 'MGMT_FEE')?.id ?? chargeTypes[0]?.id ?? '';
      const rows = await ctx.prisma.standardCharge.findMany({
        where: { organizationId: org, chargeTypeId },
        orderBy: [{ effectiveFrom: 'desc' }, { createdAt: 'desc' }],
        include: {
          property: { select: { name: true, code: true } },
          unit: { select: { name: true } },
          notices: { orderBy: { date: 'asc' }, select: { id: true, date: true, typeId: true, remark: true } },
        },
      });
      const byProperty = new Map<string, typeof rows>();
      for (const r of rows) byProperty.set(r.propertyId, [...(byProperty.get(r.propertyId) ?? []), r]);
      const asRow = (r: (typeof rows)[number]) => ({ ...r, amount: r.amount.toFixed(2) });
      const noticeIds = rows.flatMap((r) => r.notices.map((n) => n.id));
      const [files, users] = await Promise.all([
        noticeIds.length
          ? ctx.prisma.attachment.findMany({
              where: { organizationId: org, ownerType: 'PROPERTY_NOTICE', ownerId: { in: noticeIds } },
              orderBy: { createdAt: 'asc' },
              select: { id: true, ownerId: true, filename: true, mimeType: 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 nameById = new Map(users.map((u) => [u.id, u.name]));
      return {
        chargeTypeId,
        chargeTypes,
        properties,
        onDate: today.toISOString().slice(0, 10),
        rows: rows.map((r) => {
          const history = (byProperty.get(r.propertyId) ?? []).map(asRow);
          return {
            id: r.id,
            propertyId: r.propertyId,
            propertyName: propertyLabel(r.property),
            unitId: r.unitId,
            unitName: r.unit?.name ?? null,
            amount: r.amount.toFixed(2),
            effectiveFrom: r.effectiveFrom.toISOString().slice(0, 10),
            note: r.note,
            recordedByName: r.recordedByUserId ? nameById.get(r.recordedByUserId) ?? null : null,
            /** As the property's own dialog says it, against today. */
            status: isInForce(history, asRow(r), today) ? ('IN_FORCE' as const) : r.effectiveFrom.getTime() > today.getTime() ? ('ANNOUNCED' as const) : ('SUPERSEDED' as const),
            notices: r.notices.map((n) => ({
              id: n.id,
              date: n.date.toISOString().slice(0, 10),
              typeId: n.typeId,
              remark: n.remark,
              files: files.filter((f) => f.ownerId === n.id).map(({ id, filename, mimeType }) => ({ id, filename, mimeType })),
            })),
          };
        }),
        /** Tenancies keeping a price of their own; empty for one who may not read leases. */
        notFollowing: ctx.user.permissions.includes('lease.read') ? await rulesNotFollowing(ctx.prisma, org, chargeTypeId, today) : [],
      };
    }),

  /** Records a NEW figure — which is how a price changes. Optionally records the
   *  letter that announced it in the same save. */
  create: withPermission('property.update')
    .input(
      z.object({
        propertyId: z.string(),
        unitId: z.string().optional().nullable(),
        chargeTypeId: z.string(),
        amount: money,
        effectiveFrom: day,
        note: z.string().max(2000).optional().nullable(),
        notice: noticeInput.optional().nullable(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? '';
      // The notice log has its own permission; recording one from this form must
      // not be a way around it. Worded exactly as withPermission words it, so the
      // holder reads the same sentence wherever the refusal comes from.
      const needed = 'notice.create';
      if (input.notice && !ctx.user.permissions.includes(needed)) {
        throw new TRPCError({ code: 'FORBIDDEN', message: `Missing permission: ${needed}` });
      }
      if (input.notice && !(await findReferenceValue(ctx.prisma, org, 'NOTICE_TYPE', input.notice.typeId))) {
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'Notice type not found' });
      }
      return ctx.prisma.$transaction(async (tx) => {
        const created = await recordStandardCharge(tx, {
          organizationId: org,
          propertyId: input.propertyId,
          unitId: input.unitId || null,
          chargeTypeId: input.chargeTypeId,
          amount: input.amount,
          effectiveFrom: parseDay(input.effectiveFrom),
          note: input.note ?? null,
          recordedByUserId: ctx.user.id,
        });
        if (!input.notice) return { id: created.id, noticeId: null };
        const notice = await tx.propertyNotice.create({
          data: {
            organizationId: org,
            propertyId: input.propertyId,
            date: parseDay(input.notice.date),
            typeId: input.notice.typeId,
            remark: input.notice.remark,
            standardChargeId: created.id,
            recordedByUserId: ctx.user.id,
          },
          select: { id: true },
        });
        return { id: created.id, noticeId: notice.id };
      });
    }),

  /** Corrects a mistake. NOT how a price changes — the screen has to say so. */
  update: withPermission('property.update')
    .input(z.object({ id: z.string(), amount: money, effectiveFrom: day, note: z.string().max(2000).optional().nullable() }))
    .mutation(async ({ ctx, input }) => {
      await correctStandardCharge(ctx.prisma, ctx.organizationId ?? '', input.id, {
        amount: input.amount,
        effectiveFrom: parseDay(input.effectiveFrom),
        note: input.note ?? null,
      });
      return { ok: true };
    }),

  /** Removes a figure recorded by mistake. Charge rules already applied to a
   *  tenancy are that tenancy's own terms now and are left alone. */
  remove: withPermission('property.update')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      await removeStandardCharge(ctx.prisma, ctx.organizationId ?? '', input.id);
      return { ok: true };
    }),

  /** The review a change is followed by: which running tenancies differ, at what
   *  amount, and which ones are left out and why. Reads only. */
  affectedLeases: withPermission('property.read')
    .input(z.object({ id: z.string() }))
    .query(({ ctx, input }) => reviewStandardCharge(ctx.prisma, ctx.organizationId ?? '', input.id)),

  /** Applies the change to the ticked tenancies, by stepping each one's charge
   *  rule. `lease.update`, not `property.update`: this changes what a tenant is
   *  billed. (Named in full because `apply` is a reserved word in a tRPC
   *  router — it would collide with Function.prototype.apply.) */
  applyToLeases: withPermission('lease.update')
    .input(
      z.object({
        id: z.string(),
        targets: z.array(z.object({ leaseId: z.string(), unitId: z.string().optional().nullable() })).min(1),
      }),
    )
    .mutation(({ ctx, input }) =>
      applyToLeases(
        ctx.prisma,
        ctx.organizationId ?? '',
        input.id,
        input.targets.map((t) => ({ leaseId: t.leaseId, unitId: t.unitId ?? null })),
      ),
    ),
});
