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

/**
 * Whose name and address a debit note is printed under.
 *
 * The system runs as one Organization and every note has always carried its
 * heading. But the group holds its buildings through ~20 limited companies, and
 * the office bills some buildings under the owning company instead — "it
 * depends", per building. `Property.letterheadSource` is that choice.
 *
 * Shared by two callers on purpose: billing FREEZES what it resolves onto the
 * note as it is issued (`Invoice.letterheadSnapshot`), and the document service
 * PRINTS it. One function, so the note cannot be issued under one heading and
 * re-printed under another.
 */

/** Any party that can head a note: the organisation, or a landlord company. */
export interface LetterheadParty {
  name: string;
  nameZh?: string | null;
  address?: string | null;
  tel?: string | null;
  /** The organisation record has no fax column today; kept so a template can
   *  print "Fax :" the day it does, rather than smuggling it into the address. */
  fax?: string | null;
  email?: string | null;
  attention?: string | null;
}

/** The heading itself — what the template renders and what is frozen as JSON. */
export interface Letterhead {
  name: string;
  nameZh: string | null;
  address: string | null;
  tel: string | null;
  fax: string | null;
  email: string | null;
  attention: string | null;
}

/** A landlord's Tel / Email for its properties in one country. */
export interface LetterheadContact {
  countryId: string;
  tel: string | null;
  email: string | null;
}

export interface LetterheadProperty {
  letterheadSource: LetterheadSource;
  /** Where the property is: picks its landlord's contact there, if it has one.
   *  Both required, so a caller that reads a property without them does not
   *  compile — rather than quietly printing the head office's phone. */
  countryId: string | null;
  landlord: (LetterheadParty & { contacts: readonly LetterheadContact[] }) | null;
}

/** What every caller reads of a property to head its notes. One select, so a
 *  caller cannot forget the country and print the wrong office's phone. */
export const letterheadPropertySelect = {
  id: true,
  letterheadSource: true,
  countryId: true,
  landlord: { include: { contacts: { select: { countryId: true, tel: true, email: true } } } },
} as const;

const of = (p: LetterheadParty): Letterhead => ({
  name: p.name,
  nameZh: p.nameZh ?? null,
  address: p.address ?? null,
  tel: p.tel ?? null,
  fax: p.fax ?? null,
  email: p.email ?? null,
  attention: p.attention ?? null,
});

/** What a note raised against this property would print TODAY. */
export function currentLetterhead(org: LetterheadParty, property: LetterheadProperty | null): Letterhead {
  // The address is what makes the choice usable: properties.update refuses to
  // point a building at a company without one, and landlords.update refuses to
  // clear the address of a company that buildings print under, so this should be
  // unreachable. A tenant's bill is not where we want to discover otherwise, so
  // it heads back to the organisation rather than printing half a heading.
  if (property?.letterheadSource === 'LANDLORD' && property.landlord?.address) {
    // The colleagues in the property's country deal with its tenants, so their
    // Tel / Email head its notes; whatever they left blank is the company's own.
    const local = property.landlord.contacts.find((c) => c.countryId === property.countryId);
    return of({ ...property.landlord, tel: local?.tel || property.landlord.tel, email: local?.email || property.landlord.email });
  }
  return of(org);
}

/** What a note for a lease would print TODAY. A lease can take units from
 *  several purchases of a building, each with its own setting; they must agree,
 *  because one note carries one heading and the tenant is the one who would
 *  find out it was the wrong one. A lease with no units prints the organisation. */
export function leaseLetterhead(org: LetterheadParty, properties: readonly LetterheadProperty[]): Letterhead {
  const heads = properties.map((p) => currentLetterhead(org, p));
  if (heads.length === 0) return currentLetterhead(org, null);
  if (heads.some((h) => JSON.stringify(h) !== JSON.stringify(heads[0]))) {
    throw new BadRequestException("This lease's units are on properties printed under different letterheads; set those properties the same");
  }
  return heads[0];
}

/**
 * The heading a particular note prints.
 *
 * Three cases, and the third is the one that is easy to get wrong:
 *   · a note with a snapshot prints the snapshot — that is the whole point of
 *     freezing it, so last year's note does not move to this year's address;
 *   · a DRAFT has no snapshot and prints from the property's current setting,
 *     so the office sees what issuing it would produce;
 *   · an ISSUED note with NO snapshot predates this feature. Every one of those
 *     was printed under the organisation, so that is what it keeps printing —
 *     switching its building to a landlord letterhead today must not rewrite
 *     what a note said two years ago.
 */
export function letterheadFor(input: {
  org: LetterheadParty;
  /** The properties of the lease's units. */
  properties: readonly LetterheadProperty[];
  snapshot: unknown;
  /** The note has been issued — it carries a document number. */
  issued: boolean;
}): Letterhead {
  const snap = input.snapshot as Partial<Letterhead> | null;
  if (snap && typeof snap === 'object' && typeof snap.name === 'string') return of(snap as LetterheadParty);
  return input.issued ? of(input.org) : leaseLetterhead(input.org, input.properties);
}
