import { BadRequestException } from '@nestjs/common';

/**
 * App-layer bound check for period + extra night indexes on a hotel
 * stay. The DB has an absolute-max CHECK (0..99) as a last-resort
 * guard, but this catches the more common mistake — a stale FE
 * payload pointing at a night index outside the parent stay's window
 * — with a caller-friendly message.
 *
 * Called from every hotel save path (quote, booking, quick-booking,
 * convert-from-quote) before persistence.
 */
interface WithNights {
  nights?: number[];
}

export function assertNightsInRange(
  periods: WithNights[] | null | undefined,
  extras: WithNights[] | null | undefined,
  stayNights: number,
): void {
  if (!stayNights || stayNights < 1) return;
  const bad: string[] = [];
  const check = (rows: WithNights[] | null | undefined, label: string) => {
    if (!Array.isArray(rows)) return;
    rows.forEach((r, i) => {
      if (!Array.isArray(r.nights)) return;
      for (const n of r.nights) {
        if (!Number.isInteger(n) || n < 0 || n >= stayNights) {
          bad.push(`${label} #${i + 1} night ${n}`);
          return; // one message per row is enough
        }
      }
    });
  };
  check(periods, 'Room booking');
  check(extras, 'Extra');
  if (bad.length > 0) {
    throw new BadRequestException(
      `Hotel stay covers ${stayNights} night(s); the following rows point outside that window: ${bad.join(', ')}.`,
    );
  }
}
