import { BadRequestException, ConflictException, Injectable } from '@nestjs/common';
import type { NumberSequence, Prisma } from '@prisma/client';
import { hkDay } from './hk-date';
import { type NumberFormat, parseParts, periodOf, renderNumber } from './number-format';

/**
 * Per-organization, per-document-type running numbers. The atomic increment
 * inside the caller's transaction row-locks the count, so two concurrent
 * issues can never produce the same number. Replaces the legacy str_pad(id, 8)
 * scattered across controllers.
 *
 * The office decides both halves of it: the format — laid out as the ERP's,
 * symbol, special strings, company code, year, month, day and serial in its own
 * order, and whether the count restarts — on the Settings page, and, when it
 * wants, the number of one particular document, typed in as it is created.
 * A typed number never moves the count; the count steps over any number a
 * typed one has already taken, so the two can be mixed freely.
 *
 * A number carrying the company code is counted per company, as the ERP counts
 * it: DN-WF261001 and DN-AB261001 are both the first of the month. Year, month
 * and day are the document's own — a debit note's issue date, a receipt's
 * received date — in Hong Kong.
 */

/** The documents numbered here. */
export const NUMBERED_DOCS = ['INVOICE', 'RECEIPT', 'DEPOSIT_RECEIPT', 'DEPOSIT', 'LEASE', 'PROPERTY'] as const;
export type NumberedDoc = (typeof NUMBERED_DOCS)[number];

/** What a number is drawn for: the document's date, whose year, month and day
 *  go in it, and the properties it concerns, whose landlord gives the company
 *  code. */
export interface NumberFor {
  date: Date;
  propertyIds: (string | null | undefined)[];
}

/** A landlord company, as far as a number needs it. */
export interface NumberCompany {
  id: string;
  code: string;
}

type Sequence = Pick<NumberSequence, 'id' | 'prefix' | 'text1' | 'text2' | 'parts' | 'padding' | 'resetPeriod'>;
type NumberedTables = Pick<Prisma.TransactionClient, 'invoice' | 'receipt' | 'deposit' | 'lease' | 'property'>;
type CounterKey = { sequenceId: string; scope: string; periodKey: string };

/** What a typed number may look like: letters, digits and - _ / . , up to 40,
 *  starting with a letter or digit — enough for "DN-001932" or "WF/2026/001". */
const TYPED = /^[A-Za-z0-9][A-Za-z0-9\-_/.]{0,39}$/;

/** Whether a number is already on a document of this type. The columns are
 *  unique across the whole database, not per organisation, so this is too. */
export async function numberTaken(db: NumberedTables, docType: NumberedDoc, number: string): Promise<boolean> {
  switch (docType) {
    case 'INVOICE':
      return (await db.invoice.count({ where: { number } })) > 0;
    // Both kinds of receipt share the receipts table and its unique number.
    case 'RECEIPT':
    case 'DEPOSIT_RECEIPT':
      return (await db.receipt.count({ where: { number } })) > 0;
    case 'DEPOSIT':
      return (await db.deposit.count({ where: { number } })) > 0;
    case 'LEASE':
      return (await db.lease.count({ where: { reference: number } })) > 0;
    case 'PROPERTY':
      return (await db.property.count({ where: { code: number } })) > 0;
  }
}

export function formatOf(seq: Sequence): NumberFormat {
  return { prefix: seq.prefix, text1: seq.text1, text2: seq.text2, parts: parseParts(seq.parts), padding: seq.padding };
}

/** The count a number is drawn from: the company's own when the number carries
 *  its code, and this year's or month's when it restarts. */
export function counterKey(seq: Sequence, company: NumberCompany | null, date: string): CounterKey {
  const scope = parseParts(seq.parts).includes('COMPANY') ? (company?.id ?? '') : '';
  return { sequenceId: seq.id, scope, periodKey: periodOf(seq.resetPeriod, date) };
}

/** The number the next document of this type will get, without taking it —
 *  for the Settings page to show what its format produces. */
export async function previewNumber(
  db: NumberedTables & Pick<Prisma.TransactionClient, 'numberCounter'>,
  seq: Sequence,
  docType: NumberedDoc,
  company: NumberCompany | null,
  now = new Date(),
): Promise<string> {
  const date = hkDay(now);
  const counter = await db.numberCounter.findUnique({ where: { sequenceId_scope_periodKey: counterKey(seq, company, date) } });
  const render = (serial: number) => renderNumber(formatOf(seq), { company: company?.code ?? '', date, serial });
  let serial = counter?.nextValue ?? 1;
  // Stepping over typed numbers exactly as nextNumber will.
  while (await numberTaken(db, docType, render(serial))) serial++;
  return render(serial);
}

/** The next number in the organisation's sequence for this document type. */
export async function nextNumber(tx: Prisma.TransactionClient, organizationId: string, docType: NumberedDoc, on: NumberFor): Promise<string> {
  const seq = await tx.numberSequence.findUnique({
    where: { organizationId_docType: { organizationId, docType } },
  });
  if (!seq) throw new Error(`No number sequence configured for ${docType}`);

  const format = formatOf(seq);
  const company = format.parts.includes('COMPANY') ? await companyOf(tx, organizationId, on.propertyIds) : null;
  const date = hkDay(on.date);
  const key = counterKey(seq, company, date);
  const render = (serial: number) => renderNumber(format, { company: company?.code ?? '', date, serial });

  // A number someone typed in may sit where the count has got to; step past
  // it rather than collide with it.
  let serial = await take(tx, key);
  while (await numberTaken(tx, docType, render(serial))) serial = await take(tx, key);
  return render(serial);
}

/** The number the office typed for this document, checked; or, when it typed
 *  none, the next in sequence. */
export async function assignNumber(
  tx: Prisma.TransactionClient,
  organizationId: string,
  docType: NumberedDoc,
  typed: string | null | undefined,
  on: NumberFor,
): Promise<string> {
  const number = typed?.trim();
  if (!number) return nextNumber(tx, organizationId, docType, on);
  if (!TYPED.test(number)) {
    throw new BadRequestException('A document number may use only letters, digits and - _ / . — up to 40 characters');
  }
  if (await numberTaken(tx, docType, number)) throw new ConflictException(`Number ${number} is already used`);
  return number;
}

@Injectable()
export class NumberService {
  next(tx: Prisma.TransactionClient, organizationId: string, docType: NumberedDoc, on: NumberFor): Promise<string> {
    return nextNumber(tx, organizationId, docType, on);
  }

  assign(tx: Prisma.TransactionClient, organizationId: string, docType: NumberedDoc, typed: string | null | undefined, on: NumberFor): Promise<string> {
    return assignNumber(tx, organizationId, docType, typed, on);
  }
}

/** Takes the next count, row-locking it until the transaction ends. The first
 *  number of a company or a period starts its count, in the same statement, so
 *  two firsts at once cannot both start it — one waits, then takes the second. */
async function take(tx: Prisma.TransactionClient, key: CounterKey): Promise<number> {
  await tx.$executeRaw`
    INSERT INTO number_counters (sequenceId, scope, periodKey, nextValue)
    VALUES (${key.sequenceId}, ${key.scope}, ${key.periodKey}, 2)
    ON DUPLICATE KEY UPDATE nextValue = nextValue + 1`;
  // Read back in the same transaction: it sees its own write.
  const counter = await tx.numberCounter.findUniqueOrThrow({ where: { sequenceId_scope_periodKey: key } });
  return counter.nextValue - 1;
}

/** The one landlord company a document belongs to, for a number that carries
 *  its code. A document of no company, or of two, cannot be given one — the
 *  office sets the property's landlord, splits the payment, or types the number. */
async function companyOf(tx: Prisma.TransactionClient, organizationId: string, propertyIds: NumberFor['propertyIds']): Promise<NumberCompany> {
  const ids = [...new Set(propertyIds.filter((id): id is string => !!id))];
  const properties = await tx.property.findMany({
    where: { id: { in: ids }, organizationId },
    select: { name: true, landlord: { select: { id: true, code: true } } },
  });
  if (properties.length === 0) {
    throw new BadRequestException('This document is not for a lease, so its number has no company code to carry; link it to a lease, or type its number');
  }
  const unowned = properties.find((p) => !p.landlord);
  if (unowned) throw new BadRequestException(`${unowned.name} has no landlord, so the number has no company code to carry; set the property's landlord first`);
  const companies = new Map(properties.map((p) => [p.landlord!.id, p.landlord!]));
  if (companies.size > 1) throw new BadRequestException('These debit notes belong to different landlord companies; record a separate payment for each');
  return [...companies.values()][0];
}
