/**
 * Which itinerary lines a booking change request touches — pure helpers
 * shared by ChangeRequestService (next-day routing + Approvals badge) and
 * the Movement Dashboard (row chips + lock).
 *
 * A change request stores the proposed booking (`payload`,
 * UpdateBookingDto-shaped) and the booking as it was at submission
 * (`before_snapshot`, BookingService.findById shape). Lines are matched
 * by id per type; a type the payload leaves out is untouched.
 */
import { addDaysIso, todayInTz } from './booking-approval-triggers';

export type ChangedLineType = 'transport' | 'activity' | 'special';
export type LineChange = 'added' | 'edited' | 'removed';

export interface ChangedLine {
  type: ChangedLineType;
  /** Line id; null for a line added by the request. */
  id: string | null;
  /** Service date (YYYY-MM-DD) — the old date for a removed line. Both
   *  dates count for an edit that moves the line. */
  dates: string[];
  change: LineChange;
}

const ITEM_KEYS: Record<ChangedLineType, string> = {
  transport: 'transport_items',
  activity: 'activity_items',
  special: 'special_items',
};

/** Keys that carry no service change (ordering, FE link keys, flags). */
const IGNORED_KEYS = new Set([
  'id',
  'sort_order',
  'refresh_tax',
  'link_key',
  'linked_activity_link_key',
  'sync_driver_to_masters',
]);

type Item = Record<string, unknown>;

function dateOf(v: unknown): string {
  if (!v) return '';
  if (v instanceof Date) return v.toISOString().slice(0, 10);
  return String(v).slice(0, 10);
}

/** Normalise a scalar so '5.00' / 5 and null / '' compare equal. */
function norm(key: string, v: unknown): string {
  if (v === null || v === undefined || v === '') return '';
  if (key === 'date' || key.endsWith('_date')) return dateOf(v);
  if (key.endsWith('_time')) return String(v).slice(0, 5);
  if (typeof v === 'number' || (typeof v === 'string' && /^-?\d+(\.\d+)?$/.test(v.trim()))) {
    return String(Number(v));
  }
  return String(v).trim();
}

function isEdited(next: Item, prev: Item): boolean {
  for (const [key, value] of Object.entries(next)) {
    if (IGNORED_KEYS.has(key)) continue;
    // Nested shapes (suppliers, periods) differ between the DTO and the
    // entity — only scalar fields are compared.
    if (value !== null && typeof value === 'object') continue;
    if (norm(key, value) !== norm(key, prev[key])) return true;
  }
  return false;
}

function asItems(v: unknown): Item[] | null {
  return Array.isArray(v) ? (v.filter((x) => x && typeof x === 'object') as Item[]) : null;
}

/** An activity line = one activity on one date; its age-group rows
 *  (adult / child) are stored as separate items. */
function activityLineOf(i: Item): string {
  return `${String(i.activity_id ?? '')}|${dateOf(i.date)}`;
}

function quantityOf(i: Item): number {
  const n = Number(i.quantity);
  return Number.isFinite(n) ? n : 1;
}

/** Added / edited / removed transport, activity and special lines. */
export function diffChangeRequestLines(
  beforeSnapshot: Record<string, unknown> | null | undefined,
  payload: Record<string, unknown> | null | undefined,
): ChangedLine[] {
  if (!beforeSnapshot || !payload) return [];
  const out: ChangedLine[] = [];
  for (const type of Object.keys(ITEM_KEYS) as ChangedLineType[]) {
    const next = asItems(payload[ITEM_KEYS[type]]);
    if (!next) continue;
    const prev = asItems(beforeSnapshot[ITEM_KEYS[type]]) ?? [];
    const prevById = new Map(prev.filter((p) => p.id).map((p) => [String(p.id), p]));
    const isActivity = type === 'activity';
    // Activity lines still present in the request (by activity + date).
    const nextActivityLines = new Set(isActivity ? next.map(activityLineOf) : []);
    const addedActivityLines = new Set<string>();
    const seen = new Set<string>();
    for (const n of next) {
      const id = n.id ? String(n.id) : null;
      const p = id ? prevById.get(id) : undefined;
      if (!p) {
        // One activity line is saved as one row per age group — count
        // the line once.
        if (isActivity) {
          const key = activityLineOf(n);
          if (addedActivityLines.has(key)) continue;
          addedActivityLines.add(key);
        }
        out.push({ type, id: null, dates: [dateOf(n.date)].filter(Boolean), change: 'added' });
        continue;
      }
      seen.add(id as string);
      if (isEdited(n, p)) {
        const dates = Array.from(new Set([dateOf(n.date), dateOf(p.date)].filter(Boolean)));
        out.push({ type, id, dates, change: 'edited' });
      }
    }
    for (const [id, p] of prevById) {
      if (seen.has(id)) continue;
      const dates = [dateOf(p.date)].filter(Boolean);
      if (isActivity) {
        // The editor leaves zero-quantity age-group rows (e.g. "child,
        // 0") out of the request — not a removal.
        if (quantityOf(p) === 0) continue;
        // An age group dropped from a line that stays is an edit of
        // that line, not a removal.
        if (nextActivityLines.has(activityLineOf(p))) {
          out.push({ type, id, dates, change: 'edited' });
          continue;
        }
      }
      out.push({ type, id, dates, change: 'removed' });
    }
  }
  return out;
}

/**
 * Check-in dates of hotel stays the request adds / edits / removes.
 * Hotels aren't on the Movement Dashboard, so these never lock it or
 * alert Ops — they only tell a hotel change apart from a price-only one
 * on the Approvals list. Room / period detail shows in the subtotal.
 */
export function hotelChangeDates(
  beforeSnapshot: Record<string, unknown> | null | undefined,
  payload: Record<string, unknown> | null | undefined,
): string[] {
  if (!beforeSnapshot || !payload) return [];
  const next = asItems(payload.hotel_items);
  if (!next) return [];
  const prev = asItems(beforeSnapshot.hotel_items) ?? [];
  const prevById = new Map(prev.filter((p) => p.id).map((p) => [String(p.id), p]));
  const dates = new Set<string>();
  const seen = new Set<string>();
  for (const n of next) {
    const p = n.id ? prevById.get(String(n.id)) : undefined;
    if (p) seen.add(String(n.id));
    if (!p || isEdited(n, p)) {
      dates.add(dateOf(n.check_in_date));
      if (p) dates.add(dateOf(p.check_in_date));
    }
  }
  for (const [id, p] of prevById) if (!seen.has(id)) dates.add(dateOf(p.check_in_date));
  dates.delete('');
  return Array.from(dates).sort();
}

/** Default Ops alert window: today + tomorrow. */
export const DEFAULT_OPS_ALERT_WINDOW_DAYS = 1;

/** Sorted, unique service dates the request touches. */
export function changeDates(lines: ChangedLine[]): string[] {
  return Array.from(new Set(lines.flatMap((l) => l.dates))).sort();
}

/**
 * Days from today (destination tz) to the earliest changed service that
 * falls within the Ops alert window — 0 = today, 1 = tomorrow … up to
 * `windowDays` — else null. Price-only requests (no lines) are null.
 */
export function travelsWithinDays(
  lines: ChangedLine[],
  destTz: string | null | undefined,
  windowDays: number,
  now?: string,
): number | null {
  const today = now ?? todayInTz(destTz);
  const window = Math.max(0, Math.floor(Number(windowDays) || 0));
  const dates = new Set(lines.flatMap((l) => l.dates));
  for (let d = 0; d <= window; d++) {
    if (dates.has(addDaysIso(today, d))) return d;
  }
  return null;
}

/** "today" / "tomorrow" / "in 3 days". */
export function travelsLabel(days: number): string {
  if (days === 0) return 'today';
  if (days === 1) return 'tomorrow';
  return `in ${days} days`;
}

/** Ops alert window (tenant_settings.ops_alert_window_days). */
export async function loadOpsAlertWindow(
  manager: { query: (sql: string, params: unknown[]) => Promise<unknown> },
  tenantId: string,
): Promise<number> {
  const rows = (await manager.query(
    `SELECT ops_alert_window_days FROM tenant_settings
      WHERE tenant_id = $1 AND is_deleted = false LIMIT 1`,
    [tenantId],
  )) as Array<{ ops_alert_window_days: number | null }>;
  const raw = rows?.[0]?.ops_alert_window_days;
  return raw === null || raw === undefined ? DEFAULT_OPS_ALERT_WINDOW_DAYS : Number(raw);
}
