import type { LetterheadSource, Prisma, PrismaClient } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { parseDay } from '../../common/hk-date';
import { buildingKey, buildingName } from '../../common/lease-premises';
import { assignNumber, nextNumber } from '../../common/number.service';
import { findReferenceValue, referenceOptions } from '../reference-lookup';
import { router, withPermission } from '../trpc';

/** Whose letterhead this building's debit notes carry. The organisation is what
 *  every note has always printed and stays the default. */
const letterheadSource = z.enum(['ORGANIZATION', 'LANDLORD']);

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');

/** A property is one purchase: its number, the purchase, the sale once there is
 *  one, and the government lease the land is held under. Blank is null. */
const purchaseFields = {
  /** Typed, or blank for the PROPERTY sequence to draw (see propertyCode). */
  code: z.string().optional().nullable(),
  completionDate: day.optional().nullable(),
  purchasePrice: money.optional().nullable(),
  saleCompletionDate: day.optional().nullable(),
  salePrice: money.optional().nullable(),
  landLeaseTerm: z.string().max(191).optional().nullable(),
  landLeaseCommencement: day.optional().nullable(),
};
type PurchaseInput = { [K in keyof typeof purchaseFields]?: z.infer<(typeof purchaseFields)[K]> };

const dayOrNull = (d: string | null | undefined): Date | null => (d ? parseDay(d) : null);

/** The purchase fields a save sent, as stored; one it left out is left alone,
 *  as every other partial save here. The number is not among them: propertyCode
 *  draws it. */
type PurchaseData = Pick<
  Prisma.PropertyUncheckedCreateInput,
  'completionDate' | 'purchasePrice' | 'saleCompletionDate' | 'salePrice' | 'landLeaseTerm' | 'landLeaseCommencement'
>;
function purchaseData(input: PurchaseInput): PurchaseData {
  const data: PurchaseData = {};
  if (input.completionDate !== undefined) data.completionDate = dayOrNull(input.completionDate);
  if (input.purchasePrice !== undefined) data.purchasePrice = input.purchasePrice || null;
  if (input.saleCompletionDate !== undefined) data.saleCompletionDate = dayOrNull(input.saleCompletionDate);
  if (input.salePrice !== undefined) data.salePrice = input.salePrice || null;
  if (input.landLeaseTerm !== undefined) data.landLeaseTerm = input.landLeaseTerm?.trim() || null;
  if (input.landLeaseCommencement !== undefined) data.landLeaseCommencement = dayOrNull(input.landLeaseCommencement);
  return data;
}

/** The building's name as another purchase of it already spells it, so every
 *  purchase of one building prints one name; or as typed, for a new building.
 *  The match ignores case through the column's collation (MySQL's default is
 *  case-insensitive), as the lease form's grouping does (buildingKey). */
async function onFileName(db: Prisma.TransactionClient, organizationId: string, name: string, exceptId: string | null = null): Promise<string> {
  const typed = buildingName(name);
  const same = await db.property.findFirst({
    where: { organizationId, name: typed, ...(exceptId ? { id: { not: exceptId } } : {}) },
    orderBy: { createdAt: 'asc' },
    select: { name: true },
  });
  return same && buildingKey(same.name) === buildingKey(typed) ? same.name : typed;
}

/** A sale completes after the purchase it ends — the other way round is a date
 *  typed into the wrong box. */
function checkSale(completionDate: Date | null, saleCompletionDate: Date | null): void {
  if (completionDate && saleCompletionDate && saleCompletionDate < completionDate) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'A property cannot be sold before its purchase completed' });
  }
}

/** The property's number: the one typed; or, once its landlord and completion
 *  date are known, the next of the PROPERTY sequence — P-WF240301, counted per
 *  company in the month the purchase completed. Drawn once: a number already on
 *  the property stays when the date or the landlord changes; clearing it is
 *  asking for a new one. */
async function propertyCode(
  tx: Prisma.TransactionClient,
  organizationId: string,
  property: { id: string; code: string | null; landlordId: string | null; completionDate: Date | null },
  typed: string | null | undefined,
): Promise<string | null> {
  const wanted = typed === undefined ? property.code : typed?.trim() || null;
  if (wanted && wanted === property.code) return wanted;
  if (wanted) return assignNumber(tx, organizationId, 'PROPERTY', wanted, { date: new Date(), propertyIds: [] });
  if (!property.landlordId || !property.completionDate) return null;
  return nextNumber(tx, organizationId, 'PROPERTY', { date: property.completionDate, propertyIds: [property.id] });
}

/** The owning company and the category both arrive as bare ids, so both are
 *  resolved against this org (and, for the category, against its own list)
 *  before they are stored. Null clears either.
 *
 *  `currentLandlordId` is the owner the property already names. An archived
 *  company is not offered for a NEW assignment, but it stays valid where it is
 *  already stored — same stance findReferenceValue takes on a retired value:
 *  taking something out of circulation must never make the records that refer
 *  to it unsaveable. */
async function checkOwnership(
  prisma: PrismaClient,
  organizationId: string | undefined,
  landlordId: string | null,
  categoryId: string | null,
  currentLandlordId: string | null = null,
  /** The letterhead this save lands on, with the company it would print — which
   *  is the one already stored when the save does not mention it. */
  letterhead: { source: LetterheadSource; landlordId: string | null } | null = null,
): Promise<void> {
  if (letterhead?.source === 'LANDLORD') {
    // A heading with a company name and no address is not a letterhead, and the
    // tenant is the one who would find that out. Refused here, at the only place
    // the choice can be made; landlords.router refuses the other way in, which
    // is clearing the address afterwards.
    if (!letterhead.landlordId) {
      throw new TRPCError({ code: 'BAD_REQUEST', message: 'Choose the owning company before printing debit notes under it' });
    }
    const owner = await prisma.landlord.findFirst({ where: { id: letterhead.landlordId, organizationId }, select: { address: true } });
    if (!owner) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Landlord not found' });
    if (!owner.address?.trim()) {
      throw new TRPCError({ code: 'BAD_REQUEST', message: 'That company has no address on file, so its letterhead cannot be printed' });
    }
  }
  if (landlordId) {
    const unchanged = landlordId === currentLandlordId;
    const found = await prisma.landlord.findFirst({
      where: { id: landlordId, organizationId, ...(unchanged ? {} : { deletedAt: null }) },
      select: { id: true },
    });
    if (!found) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Landlord not found' });
  }
  if (categoryId) {
    const found = await findReferenceValue(prisma, organizationId, 'PROPERTY_CATEGORY', categoryId);
    if (!found) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Property category not found' });
  }
}

/** Where the property is, which picks its landlord's local contact for the
 *  letterhead. A bare id, like the category: resolved against this org's own
 *  list before it is stored. */
async function checkCountry(prisma: PrismaClient, organizationId: string | undefined, countryId: string | null | undefined): Promise<void> {
  if (countryId && !(await findReferenceValue(prisma, organizationId, 'COUNTRY', countryId))) {
    throw new TRPCError({ code: 'BAD_REQUEST', message: 'Country not found' });
  }
}

export const propertiesRouter = router({
  list: withPermission('property.read')
    .input(z.object({ includeArchived: z.boolean().optional() }).optional())
    .query(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? undefined;
      const rows = await ctx.prisma.property.findMany({
        where: {
          organizationId: org,
          ...(input?.includeArchived ? {} : { deletedAt: null }),
        },
        orderBy: [{ name: 'asc' }, { code: 'asc' }],
        include: {
          landlord: { select: { code: true, name: true, nameZh: true } },
          _count: { select: { units: { where: { deletedAt: null } } } },
        },
      });
      // A lease names no property: it is on each purchase it has units on.
      const leaseUnits = await ctx.prisma.leaseUnit.findMany({
        where: { lease: { organizationId: org, deletedAt: null }, unit: { propertyId: { in: rows.map((p) => p.id) } } },
        select: { leaseId: true, unit: { select: { propertyId: true } } },
      });
      const leasesOn = new Map<string, Set<string>>();
      for (const lu of leaseUnits) leasesOn.set(lu.unit.propertyId, (leasesOn.get(lu.unit.propertyId) ?? new Set()).add(lu.leaseId));
      // Categories are reference values, not a relation, so they can't be joined:
      // one lookup for the whole page rather than one per row.
      const categories = await ctx.prisma.referenceValue.findMany({
        where: { organizationId: org, domain: 'PROPERTY_CATEGORY' },
        select: { id: true, nameEn: true, nameZh: true },
      });
      const category = new Map(categories.map((c) => [c.id, c]));
      // Both names travel, never one picked here: the same page also renders
      // these through a picker that follows the UI language, and a row that
      // disagreed with the dialog above it is worse than a longer payload.
      return rows.map((p) => ({
        id: p.id,
        name: p.name,
        code: p.code,
        address: p.address,
        regionId: p.regionId,
        landlordId: p.landlordId,
        landlordCode: p.landlord?.code ?? null,
        landlordName: p.landlord?.name ?? null,
        landlordNameZh: p.landlord?.nameZh ?? null,
        categoryId: p.categoryId,
        categoryNameEn: (p.categoryId ? category.get(p.categoryId)?.nameEn : null) ?? null,
        categoryNameZh: (p.categoryId ? category.get(p.categoryId)?.nameZh : null) ?? null,
        countryId: p.countryId,
        letterheadSource: p.letterheadSource,
        completionDate: p.completionDate,
        purchasePrice: p.purchasePrice?.toFixed(2) ?? null,
        saleCompletionDate: p.saleCompletionDate,
        salePrice: p.salePrice?.toFixed(2) ?? null,
        units: p._count.units,
        leases: leasesOn.get(p.id)?.size ?? 0,
        archived: p.deletedAt != null,
      }));
    }),

  /** The pickers the property form needs: the buildings already on file, who can
   *  own it, what it can be, and what kind of paperwork can be filed against it.
   *  `address` travels with each company because the letterhead choice depends
   *  on it — the form can grey out a company it would only be refused for. */
  formData: withPermission('property.read').query(async ({ ctx }) => {
    const org = ctx.organizationId ?? undefined;
    const [names, landlords, categories, documentTypes, countries] = await Promise.all([
      // Another purchase of a building is typed under the same name; offering
      // the names on file is what keeps it the same.
      ctx.prisma.property.findMany({ where: { organizationId: org, deletedAt: null }, orderBy: { name: 'asc' }, select: { name: true }, distinct: ['name'] }),
      ctx.prisma.landlord.findMany({
        where: { organizationId: org, isActive: true, deletedAt: null },
        orderBy: [{ sortOrder: 'asc' }, { code: 'asc' }],
        select: { id: true, code: true, name: true, nameZh: true, address: true },
      }),
      referenceOptions(ctx.prisma, org, 'PROPERTY_CATEGORY'),
      referenceOptions(ctx.prisma, org, 'PROPERTY_DOCUMENT_TYPE'),
      referenceOptions(ctx.prisma, org, 'COUNTRY'),
    ]);
    const buildings = new Map(names.map((p) => [buildingKey(p.name), p.name]));
    return { buildings: [...buildings.values()], landlords, categories, documentTypes, countries };
  }),

  get: withPermission('property.read')
    .input(z.object({ id: z.string() }))
    .query(async ({ ctx, input }) => {
      const p = await ctx.prisma.property.findFirst({
        where: { id: input.id, organizationId: ctx.organizationId ?? undefined },
        include: {
          landlord: { select: { code: true, name: true, address: true } },
          units: { where: { deletedAt: null }, orderBy: { name: 'asc' }, select: { id: true, name: true } },
        },
      });
      if (!p) throw new TRPCError({ code: 'NOT_FOUND' });
      return {
        id: p.id,
        name: p.name,
        code: p.code,
        address: p.address ?? '',
        regionId: p.regionId,
        landlordId: p.landlordId,
        landlordCode: p.landlord?.code ?? null,
        landlordName: p.landlord?.name ?? null,
        // The heading a note for this building would print under today, so the
        // form can show it rather than make the user guess what the switch does.
        landlordAddress: p.landlord?.address ?? null,
        categoryId: p.categoryId,
        countryId: p.countryId,
        letterheadSource: p.letterheadSource,
        completionDate: p.completionDate?.toISOString().slice(0, 10) ?? null,
        purchasePrice: p.purchasePrice?.toFixed(2) ?? null,
        saleCompletionDate: p.saleCompletionDate?.toISOString().slice(0, 10) ?? null,
        salePrice: p.salePrice?.toFixed(2) ?? null,
        landLeaseTerm: p.landLeaseTerm,
        landLeaseCommencement: p.landLeaseCommencement?.toISOString().slice(0, 10) ?? null,
        units: p.units,
      };
    }),

  create: withPermission('property.create')
    .input(
      z.object({
        name: z.string().min(1),
        address: z.string().optional(),
        regionId: z.string().optional(),
        landlordId: z.string().optional().nullable(),
        categoryId: z.string().optional().nullable(),
        countryId: z.string().optional().nullable(),
        letterheadSource: letterheadSource.optional(),
        ...purchaseFields,
        units: z.array(z.object({ name: z.string().min(1) })).optional(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      checkSale(dayOrNull(input.completionDate), dayOrNull(input.saleCompletionDate));
      await checkOwnership(
        ctx.prisma,
        ctx.organizationId ?? undefined,
        input.landlordId ?? null,
        input.categoryId ?? null,
        null,
        input.letterheadSource ? { source: input.letterheadSource, landlordId: input.landlordId ?? null } : null,
      );
      await checkCountry(ctx.prisma, ctx.organizationId ?? undefined, input.countryId);
      return ctx.prisma.$transaction(async (tx) => {
        const property = await tx.property.create({
          data: {
            organizationId: ctx.organizationId ?? '',
            name: await onFileName(tx, ctx.organizationId ?? '', input.name),
            address: input.address ?? null,
            regionId: input.regionId ?? null,
            landlordId: input.landlordId || null,
            categoryId: input.categoryId || null,
            countryId: input.countryId || null,
            ...(input.letterheadSource ? { letterheadSource: input.letterheadSource } : {}),
            ...purchaseData(input),
            units: input.units?.length ? { create: input.units.map((u) => ({ name: u.name })) } : undefined,
          },
        });
        const code = await propertyCode(tx, ctx.organizationId ?? '', property, input.code);
        if (code) await tx.property.update({ where: { id: property.id }, data: { code } });
        return { id: property.id };
      });
    }),

  /** Edit the property's own fields and (optionally) its units — rename, add, or
   * remove. A unit used by a lease cannot be removed. */
  update: withPermission('property.update')
    .input(
      z.object({
        id: z.string(),
        name: z.string().min(1),
        address: z.string().optional().nullable(),
        regionId: z.string().optional().nullable(),
        landlordId: z.string().optional().nullable(),
        categoryId: z.string().optional().nullable(),
        countryId: z.string().optional().nullable(),
        letterheadSource: letterheadSource.optional(),
        ...purchaseFields,
        units: z.array(z.object({ id: z.string().optional(), name: z.string().min(1) })).optional(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? undefined;
      // Read the owner it already names before validating: re-saving a property
      // must not fail because its company has since been archived.
      const current = await ctx.prisma.property.findFirst({
        where: { id: input.id, organizationId: org, deletedAt: null },
        select: { landlordId: true, letterheadSource: true, code: true, completionDate: true, saleCompletionDate: true },
      });
      const completionDate = input.completionDate !== undefined ? dayOrNull(input.completionDate) : current?.completionDate ?? null;
      checkSale(completionDate, input.saleCompletionDate !== undefined ? dayOrNull(input.saleCompletionDate) : current?.saleCompletionDate ?? null);
      // The letterhead is checked against the company this save LANDS on — a
      // form that switches the owner and the letterhead in one go must be judged
      // on the pair it is asking for, not on what is stored now.
      const landing = input.landlordId !== undefined ? input.landlordId || null : current?.landlordId ?? null;
      const heading = input.letterheadSource ?? current?.letterheadSource ?? null;
      await checkOwnership(
        ctx.prisma,
        org,
        input.landlordId ?? null,
        input.categoryId ?? null,
        current?.landlordId ?? null,
        heading ? { source: heading, landlordId: landing } : null,
      );
      await checkCountry(ctx.prisma, org, input.countryId);
      return ctx.prisma.$transaction(async (tx) => {
        // org-scoped existence check — a caller can't edit another org's row by id.
        const prop = await tx.property.findFirst({ where: { id: input.id, organizationId: org, deletedAt: null }, select: { id: true } });
        if (!prop) throw new TRPCError({ code: 'NOT_FOUND' });
        await tx.property.update({
          where: { id: input.id },
          data: {
            name: await onFileName(tx, org ?? '', input.name, input.id),
            address: input.address ?? null,
            // Only touch regionId when the caller sent it (form doesn't surface it).
            ...(input.regionId !== undefined ? { regionId: input.regionId || null } : {}),
            // Same rule for the two new ones: a caller that doesn't send them
            // (an older client, a partial save) must not blank them.
            ...(input.landlordId !== undefined ? { landlordId: input.landlordId || null } : {}),
            ...(input.categoryId !== undefined ? { categoryId: input.categoryId || null } : {}),
            ...(input.countryId !== undefined ? { countryId: input.countryId || null } : {}),
            ...(input.letterheadSource !== undefined ? { letterheadSource: input.letterheadSource } : {}),
            ...purchaseData(input),
          },
        });
        // Drawn after the save, so the company it is counted under is the one
        // this save lands on.
        const code = await propertyCode(tx, org ?? '', { id: input.id, code: current?.code ?? null, landlordId: landing, completionDate }, input.code);
        if (code !== (current?.code ?? null)) await tx.property.update({ where: { id: input.id }, data: { code } });
        if (input.units) {
          const existing = await tx.unit.findMany({ where: { propertyId: input.id, deletedAt: null }, select: { id: true } });
          const keep = new Set(input.units.filter((u) => u.id).map((u) => u.id!));
          const toRemove = existing.filter((u) => !keep.has(u.id));
          for (const u of toRemove) {
            const usedByLease = await tx.leaseUnit.count({ where: { unitId: u.id } });
            if (usedByLease > 0) throw new TRPCError({ code: 'CONFLICT', message: 'A unit used by a lease cannot be removed.' });
          }
          if (toRemove.length) await tx.unit.updateMany({ where: { id: { in: toRemove.map((u) => u.id) } }, data: { deletedAt: new Date() } });
          for (const u of input.units) {
            if (u.id) await tx.unit.updateMany({ where: { id: u.id, propertyId: input.id }, data: { name: u.name } });
            else await tx.unit.create({ data: { propertyId: input.id, name: u.name } });
          }
        }
        return { id: input.id };
      });
    }),

  /** Soft-delete (archive). Blocked while the property still has live leases, so
   * lease/ledger history is never orphaned behind a hidden parent. Reversible. */
  archive: withPermission('property.delete')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? undefined;
      const leases = await ctx.prisma.lease.count({ where: { organizationId: org, deletedAt: null, units: { some: { unit: { propertyId: input.id } } } } });
      if (leases > 0) {
        throw new TRPCError({ code: 'CONFLICT', message: `This property still has ${leases} lease(s); archive or reassign them first.` });
      }
      const res = await ctx.prisma.property.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('property.delete')
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const res = await ctx.prisma.property.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 };
    }),

  /** The purchase paperwork filed against a building: the agreements, the
   *  assignment, the land search, the title deeds, the floor plan, the mortgage
   *  deed, the apportionment settlement — and whatever else the office adds to
   *  the list. Staff only; the attachment service has no tenant branch for a
   *  PROPERTY owner at all.
   *
   *  The FILES move over /api/uploads (POST with ownerType=PROPERTY and
   *  documentTypeId, DELETE /api/uploads/:id, GET /api/uploads/:id) — tRPC is
   *  JSON-only and this system has exactly one upload path. What lives here is
   *  what JSON can carry: the list, and re-filing one under another type. */
  documents: withPermission('property.read')
    .input(z.object({ propertyId: z.string() }))
    .query(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? undefined;
      const property = await ctx.prisma.property.findFirst({
        where: { id: input.propertyId, organizationId: org },
        select: { id: true },
      });
      if (!property) throw new TRPCError({ code: 'NOT_FOUND', message: 'Property not found' });
      const rows = await ctx.prisma.attachment.findMany({
        where: { organizationId: org, ownerType: 'PROPERTY', ownerId: input.propertyId },
        orderBy: { createdAt: 'asc' },
      });
      // Types are reference values, not a relation, so one lookup for the page
      // rather than one per row — the shape properties.list and notices.list use.
      // Resolved WITHOUT the isActive filter the picker uses: a kind the office
      // has since retired is still what this file is.
      const [types, users] = await Promise.all([
        ctx.prisma.referenceValue.findMany({
          where: { organizationId: org, domain: 'PROPERTY_DOCUMENT_TYPE' },
          select: { id: true, nameEn: true, nameZh: true },
        }),
        ctx.prisma.user.findMany({
          where: { id: { in: [...new Set(rows.map((r) => r.uploadedByUserId).filter((v): v is string => !!v))] } },
          select: { id: true, name: true },
        }),
      ]);
      const typeById = new Map(types.map((t) => [t.id, t]));
      const nameById = new Map(users.map((u) => [u.id, u.name]));
      return rows.map((r) => ({
        id: r.id,
        filename: r.filename,
        mimeType: r.mimeType,
        sizeBytes: r.sizeBytes,
        caption: r.caption,
        documentTypeId: r.documentTypeId,
        typeNameEn: (r.documentTypeId ? typeById.get(r.documentTypeId)?.nameEn : null) ?? null,
        typeNameZh: (r.documentTypeId ? typeById.get(r.documentTypeId)?.nameZh : null) ?? null,
        uploadedByName: r.uploadedByUserId ? nameById.get(r.uploadedByUserId) ?? null : null,
        createdAt: r.createdAt,
      }));
    }),

  /** Re-file one under another type, or fix its caption. The stored file is
   *  never touched: classifying a document is not replacing it. */
  updateDocument: withPermission('property.update')
    .input(
      z.object({
        id: z.string(),
        documentTypeId: z.string().min(1),
        caption: z.string().max(191).optional().nullable(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const org = ctx.organizationId ?? undefined;
      // ownerType is part of the lookup: this procedure is gated on the property
      // permissions, so it must not be able to reach a receipt's payment proof.
      const att = await ctx.prisma.attachment.findFirst({
        where: { id: input.id, organizationId: org, ownerType: 'PROPERTY' },
        select: { id: true },
      });
      if (!att) throw new TRPCError({ code: 'NOT_FOUND', message: 'Attachment not found' });
      if (!(await findReferenceValue(ctx.prisma, org, 'PROPERTY_DOCUMENT_TYPE', input.documentTypeId))) {
        throw new TRPCError({ code: 'BAD_REQUEST', message: 'Document type not found' });
      }
      await ctx.prisma.attachment.update({
        where: { id: att.id },
        data: {
          documentTypeId: input.documentTypeId,
          // Only touched when sent, like every other partial save here.
          ...(input.caption !== undefined ? { caption: input.caption || null } : {}),
        },
      });
      return { ok: true };
    }),
});
