import { BadRequestException } from '@nestjs/common';
import type { Prisma } from '@prisma/client';

/**
 * What a tenancy is let OF, read through its units.
 *
 * A property is one purchase — units of a building bought by a company on a
 * day — and the same building is often bought more than once. A lease takes its
 * units from any of those purchases, so it names no property of its own: its
 * building, its company, its address and its letterhead are its units'
 * properties'. `checkLeaseUnits` keeps them to one building and one company as
 * a lease is saved, which is what lets every reader below take them as one.
 */

/** A building's name as stored: trimmed, single-spaced. */
export const buildingName = (name: string): string => name.trim().replace(/\s+/g, ' ');

/** A building is the properties sharing a name — matched as the office reads
 *  it, so a capital letter does not split one building in two. */
export const buildingKey = (name: string): string => buildingName(name).toLowerCase();

/** The properties a lease's units belong to, once each, in unit order. */
export function propertiesOf<P extends { id: string }>(units: readonly { unit: { property: P } }[]): P[] {
  const seen = new Map<string, P>();
  for (const { unit } of units) if (!seen.has(unit.property.id)) seen.set(unit.property.id, unit.property);
  return [...seen.values()];
}

/** Reads a lease's properties through its units — all a document's number needs
 *  of them, the company being their landlord's. */
export const leasePropertyIds = { units: { select: { unit: { select: { propertyId: true } } } } } as const;

/** The ids `leasePropertyIds` read, once each. */
export const propertyIdsOf = (lease: { units: readonly { unit: { propertyId: string } }[] }): string[] => [
  ...new Set(lease.units.map((u) => u.unit.propertyId)),
];

/** Reads a lease's properties through its units, as far as naming its building
 *  goes: `buildingOf(propertiesOf(lease.units))`. */
export const leaseBuilding = { units: { select: { unit: { select: { property: { select: { id: true, name: true } } } } } } } as const;

/** The building a lease is in, by name; empty for a lease with no units. */
export function buildingOf(properties: readonly { name: string }[]): string {
  const names = new Map<string, string>();
  for (const p of properties) if (!names.has(buildingKey(p.name))) names.set(buildingKey(p.name), p.name);
  return [...names.values()].join(' / ');
}

/** The premises' address: each purchase's own, once — usually one, since the
 *  units of a building bought at different times share it. */
export function addressOf(properties: readonly { address: string | null }[]): string | null {
  const lines = [...new Set(properties.map((p) => p.address?.trim()).filter((a): a is string => !!a))];
  return lines.length ? lines.join('\n') : null;
}

/** The premises as a document's address block prints them: the units and
 *  building on the first line, then the address one line per part. */
export function premisesLines(unitNames: string[], building: string, address: string | null): string[] {
  return [
    unitNames.length ? `${unitNames.join(', ')}, ${building}` : building,
    ...(address ?? '').split(/\s*\n\s*|,\s*(?=\S)/).filter(Boolean),
  ];
}

/**
 * The units a lease is being saved with, checked as one tenancy can hold them:
 * at least one; all in one building, of one landlord company and under one
 * letterhead — a debit note is numbered, headed and imported into the ERP under
 * one company — and every newly added one on a property that is neither
 * archived nor sold. Units the lease already holds stay valid where they are: a
 * purchase sold or archived later must not make the leases it ran unsaveable.
 *
 * Returns the properties' ids, which number the lease.
 */
export async function checkLeaseUnits(
  db: Prisma.TransactionClient,
  organizationId: string,
  unitIds: readonly string[],
  heldUnitIds: readonly string[] = [],
): Promise<string[]> {
  if (unitIds.length === 0) throw new BadRequestException('Choose at least one unit for the lease');
  const units = await db.unit.findMany({
    where: { id: { in: [...unitIds] }, property: { organizationId } },
    select: {
      id: true,
      name: true,
      property: { select: { id: true, name: true, landlordId: true, letterheadSource: true, deletedAt: true, saleCompletionDate: true } },
    },
  });
  if (units.length !== new Set(unitIds).size) throw new BadRequestException('Some units are not in this organization');
  if (new Set(units.map((u) => buildingKey(u.property.name))).size > 1) {
    throw new BadRequestException('All the units of a lease must be in one building');
  }
  if (new Set(units.map((u) => u.property.landlordId)).size > 1) {
    throw new BadRequestException('All the units of a lease must belong to one landlord company');
  }
  if (new Set(units.map((u) => u.property.letterheadSource)).size > 1) {
    throw new BadRequestException("This lease's units are on properties printed under different letterheads; set those properties the same");
  }
  const unavailable = units.find((u) => !heldUnitIds.includes(u.id) && (u.property.deletedAt || u.property.saleCompletionDate));
  if (unavailable) throw new BadRequestException(`Unit ${unavailable.name} is on a property that has been sold or archived`);
  return [...new Set(units.map((u) => u.property.id))];
}
