/**
 * TZ §4.1.15.10 — special-meal lookup against Aeroflot's `ws2` API.
 *
 * Endpoint:   POST https://www.aeroflot.ru/ws2/v.0.0.2/json/meal
 * Payload:    { origin, destination, airline, number, flight_datetime, cabin }
 * Cache:      3 hours client-side, keyed by the full payload
 * Cabin rule: if Economy meals exist for the flight, query cabin=economy;
 *             if only Business meals are defined, query cabin=business.
 *             The `is_available_now` flag in the response is ignored.
 */

import { ClientMemoryCache } from "@/shared/api/cache.js";

const ENDPOINT = "https://www.aeroflot.ru/ws2/v.0.0.2/json/meal";
const THREE_HOURS_MS = 3 * 60 * 60 * 1000;

export interface SpecialMealParams {
  origin: string;
  destination: string;
  airline: string;
  number: string;
  /** Scheduled departure UTC as "YYYY-MM-DD HH:mm:ss". */
  flightDatetimeUtc: string;
  cabin: "economy" | "business";
}

interface SpecialMealResponseShape {
  special_meals?: unknown;
  meals?: unknown;
  available?: unknown;
  is_available?: unknown;
  // `is_available_now` exists but TZ says to ignore it.
}

const cache = new ClientMemoryCache<boolean>({ max: 500, defaultTtlMs: THREE_HOURS_MS });

function cacheKey(p: SpecialMealParams): string {
  return `${p.airline}|${p.number}|${p.origin}|${p.destination}|${p.flightDatetimeUtc}|${p.cabin}`;
}

function hasSpecialMeal(body: SpecialMealResponseShape): boolean {
  // The API has gone through several shapes; accept a non-empty array on
  // special_meals / meals or a truthy available / is_available flag. We
  // intentionally do NOT look at is_available_now per TZ §4.1.15.10.
  const listLike = body.special_meals ?? body.meals;
  if (Array.isArray(listLike) && listLike.length > 0) return true;
  if (body.available === true || body.is_available === true) return true;
  return false;
}

/**
 * Fetch and cache the special-meal availability for a flight+cabin.
 * Returns `null` on network/parse errors — the caller should treat that
 * the same as "no special meal" (no banner shown).
 */
export async function fetchSpecialMealAvailability(
  p: SpecialMealParams,
  signal?: AbortSignal,
): Promise<boolean | null> {
  const key = cacheKey(p);
  const cached = cache.get(key);
  if (cached !== undefined) return cached;

  try {
    const res = await fetch(ENDPOINT, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        origin: p.origin,
        destination: p.destination,
        airline: p.airline,
        number: p.number,
        flight_datetime: p.flightDatetimeUtc,
        cabin: p.cabin,
      }),
      ...(signal ? { signal } : {}),
    });
    if (!res.ok) return null;
    const body = (await res.json()) as SpecialMealResponseShape;
    const available = hasSpecialMeal(body);
    cache.set(key, available);
    return available;
  } catch {
    return null;
  }
}

/** Test hook — reset the 3h cache. */
export function _resetSpecialMealCache(): void {
  cache.clear();
}
