import { EntityManager } from 'typeorm';

/**
 * Plain tokens for the Movement Dashboard Activity / Special templates
 * (WHATSAPP / MOVEMENT_ACTIVITY_* and MOVEMENT_SPECIAL_*). Same values
 * the planner row shows, in display form, so a template can read:
 *
 *   Date : {{date}}
 *   Guest name : {{guest_name}}
 *   PAX : {{pax}}
 *   Time : {{time}}
 *   Remarks : {{remarks}}
 */
export interface MovementItemTokenInput {
  date: string | null | undefined;
  guestName: string | null | undefined;
  guestMobile: string | null | undefined;
  adults: number;
  children: number;
  infants: number;
  childrenAges: number[];
  serviceName: string | null | undefined;
  ticketName?: string | null;
  time?: string | null;
  remarks?: string | null;
  supplierName: string;
  supplierPhone: string;
  bookingNumber: string | null | undefined;
}

export function movementItemTokens(i: MovementItemTokenInput): Record<string, unknown> {
  const remarks = (i.remarks || '').trim();
  const time = (i.time || '').trim();
  const ticket = (i.ticketName || '').trim();
  return {
    date: ddmmyyyy(i.date),
    guest_name: (i.guestName || '').trim(),
    guest_mobile: (i.guestMobile || '').trim(),
    pax: paxText(i.adults, i.children, i.infants),
    adults: i.adults,
    children: i.children,
    infants: i.infants,
    children_ages: i.childrenAges.length > 0 ? i.childrenAges.join(', ') : '',
    has_children_ages: i.childrenAges.length > 0,
    service_name: (i.serviceName || '').trim(),
    activity_name: (i.serviceName || '').trim(),
    ticket_name: ticket,
    has_ticket: !!ticket,
    time,
    has_time: !!time,
    remarks,
    has_remarks: !!remarks,
    supplier_name: i.supplierName,
    supplier_phone: i.supplierPhone,
    booking_number: i.bookingNumber || '',
  };
}

/** "2026-11-15" → "15/11/2026" (app display format). */
export function ddmmyyyy(d: string | null | undefined): string {
  if (!d) return '';
  const [y, m, day] = String(d).split('T')[0].split('-');
  return y && m && day ? `${day}/${m}/${y}` : String(d);
}

/** "1 Adult, 1 Child" / "2 Adults" / "2 Adults, 2 Children & 1 Infant". */
export function paxText(adults: number, children: number, infants: number): string {
  const parts = [`${adults} ${adults === 1 ? 'Adult' : 'Adults'}`];
  if (children > 0) parts.push(`${children} ${children === 1 ? 'Child' : 'Children'}`);
  if (infants > 0) parts.push(`${infants} ${infants === 1 ? 'Infant' : 'Infants'}`);
  return parts.length === 3 ? `${parts[0]}, ${parts[1]} & ${parts[2]}` : parts.join(', ');
}

interface ActivityLineItem {
  id: string;
  booking_id: string;
  activity_id: string;
  ticket_id?: string | null;
  date: unknown;
  sort_order?: number | null;
  adults_override?: number | null;
  children_override?: number | null;
  activity?: { age_config?: unknown } | null;
}

/**
 * Adult / Child of ONE activity line, same rule as the Movement
 * Dashboard: the line's age-group rows (same booking / activity /
 * ticket / date / sort order) summed; children older than the
 * activity's Child max age count as adults when the line carries all
 * the booking's children; a per-row override (partial cancel) wins.
 */
export async function activityLinePax(
  manager: EntityManager,
  item: ActivityLineItem,
  childAges: number[],
  tenantId: string,
): Promise<{ adults: number; children: number }> {
  const rows = (await manager.query(
    `SELECT age_group, COALESCE(SUM(quantity), 0) AS qty
       FROM booking_activity_items
      WHERE tenant_id = $1 AND booking_id = $2 AND activity_id = $3
        AND ticket_id IS NOT DISTINCT FROM $4 AND date IS NOT DISTINCT FROM $5::date
        AND COALESCE(sort_order, 0) = $6 AND is_deleted = false
      GROUP BY age_group`,
    [
      tenantId,
      item.booking_id,
      item.activity_id,
      item.ticket_id ?? null,
      item.date ? String(item.date).slice(0, 10) : null,
      item.sort_order ?? 0,
    ],
  )) as Array<{ age_group: string | null; qty: string | number }>;
  const ag: Record<string, number> = {};
  for (const r of rows) ag[(r.age_group || '').toLowerCase()] = Number(r.qty) || 0;
  const baseAdults = (ag.adult || 0) + (ag.senior || 0);
  const baseChildren = ag.child || 0;
  const bands = Array.isArray(item.activity?.age_config)
    ? (item.activity?.age_config as Array<{ label?: string; max_age?: number; enabled?: boolean }>)
    : [];
  const childBand = bands.find((c) => c.label?.toLowerCase() === 'child');
  const maxChildAge =
    childBand && childBand.enabled !== false && (childBand.max_age ?? 0) > 0
      ? (childBand.max_age as number)
      : null;
  const olderKids =
    maxChildAge != null && baseChildren === childAges.length
      ? childAges.filter((a) => a > maxChildAge).length
      : 0;
  return {
    adults: item.adults_override ?? baseAdults + olderKids,
    children: item.children_override ?? baseChildren - olderKids,
  };
}

/** The row's supplier as the tab shows it — Activity: first junction
 *  supplier, else the item's own; Special: the item's own, else the
 *  first junction supplier. Tenant-scoped (raw SQL). */
export async function primarySupplier(
  manager: EntityManager,
  kind: 'ACTIVITY' | 'SPECIAL',
  item: {
    id: string;
    supplier?: { name?: string | null; phone?: string | null } | null;
    supplier_name_text?: string | null;
    supplier_phone_text?: string | null;
  },
  tenantId: string,
): Promise<{ name: string; phone: string }> {
  const own = {
    name: item.supplier?.name ?? item.supplier_name_text ?? '',
    phone: item.supplier?.phone ?? item.supplier_phone_text ?? '',
  };
  // The Special tab shows the item's own supplier — use it when set.
  if (kind === 'SPECIAL' && (own.name || own.phone)) return own;
  const table =
    kind === 'ACTIVITY' ? 'booking_activity_item_suppliers' : 'booking_special_item_suppliers';
  const col = kind === 'ACTIVITY' ? 'activity_item_id' : 'special_item_id';
  const rows = (await manager.query(
    `SELECT COALESCE(m.name, j.supplier_name_text, '') AS name,
            COALESCE(m.phone, j.supplier_phone_text, '') AS phone
       FROM ${table} j
       LEFT JOIN suppliers m ON m.id = j.supplier_id
      WHERE j.${col} = $1 AND j.tenant_id = $2 AND j.is_deleted = false
      ORDER BY j.sort_order ASC LIMIT 1`,
    [item.id, tenantId],
  )) as Array<{ name: string; phone: string }>;
  if (rows[0] && (rows[0].name || rows[0].phone)) return rows[0];
  return own;
}
