/**
 * WhatsApp Availability Service
 *
 * Checks appointment slot availability for WhatsApp booking requests.
 */

import { convexQuery } from '@/lib/convex-client';
import { logger } from '@/lib/logger';

/**
 * Check if a time slot is available for booking.
 *
 * Calls `bookings/queries:getConflictingBookings` directly (bypassing the
 * Prisma-Convex adapter) because the generic bookings listFn is scoped by
 * userId and can't translate the (organizationId, time-range) where-shape we
 * need. The Convex query returns all active bookings whose interval overlaps
 * the proposed slot.
 *
 * @param params.organizationId - Organization to check availability within.
 * @param params.date - Slot date in `YYYY-MM-DD` format.
 * @param params.time - Slot time in `HH:mm` format.
 * @param params.duration - Slot duration in minutes (defaults to 30).
 * @param params.staffId - Optional staff member to scope the check to.
 * @param params.excludeBookingId - If provided, excludes this booking from the
 *   conflict check — used when the same booking is being rescheduled to a new slot.
 */
export async function isSlotAvailable(params: {
  organizationId: string;
  date: string;
  time: string;
  duration?: number;
  staffId?: string;
  excludeBookingId?: string;
}): Promise<boolean> {
  const {
    organizationId,
    date,
    time,
    duration = 30,
    staffId,
    excludeBookingId,
  } = params;

  try {
    // Parse the proposed slot into a [startMs, endMs) interval. Dates are
    // interpreted in the server's local timezone — matches the existing
    // behavior of other WhatsApp booking code in this service.
    const startTime = new Date(`${date}T${time}:00`);
    if (Number.isNaN(startTime.getTime())) {
      logger.warn('[whatsapp-availability] Invalid date/time, assuming available', {
        date,
        time,
      });
      return true;
    }
    const startMs = startTime.getTime();
    const endMs = startMs + duration * 60 * 1000;

    const conflicts = (await convexQuery(
      'bookings/queries:getConflictingBookings',
      {
        organizationId,
        startMs,
        endMs,
        ...(excludeBookingId ? { excludeBookingId } : {}),
        ...(staffId ? { staffMember: staffId } : {}),
      },
    )) as unknown[] | null;

    return !Array.isArray(conflicts) || conflicts.length === 0;
  } catch (error) {
    logger.warn('[whatsapp-availability] Slot check failed, assuming available', {
      error: error instanceof Error ? error.message : String(error),
    });
    return true;
  }
}
