import { StayStatus } from '@prisma/client';

export interface HeldStayWindow {
  id: string;
  status: StayStatus;
  plannedCheckOut: Date;
}

/**
 * A checked-in guest who is overdue still holds the bed until now. Bookings
 * otherwise hold it until their planned check-out.
 */
export function heldUntil(stay: Pick<HeldStayWindow, 'status' | 'plannedCheckOut'>, now = new Date()) {
  return stay.status === StayStatus.CHECKED_IN && stay.plannedCheckOut < now ? now : stay.plannedCheckOut;
}

/** Midnight today in the property's fixed India timezone. */
export function startOfTodayIST(now = new Date()): Date {
  const india = new Date(now.getTime() + 330 * 60_000).toISOString().slice(0, 10);
  return new Date(`${india}T00:00:00+05:30`);
}

/** A calendar date before today is never valid for a new booking. */
export function bookingStartsBeforeToday(checkIn: Date, now = new Date()): boolean {
  return checkIn < startOfTodayIST(now);
}

/** Today uses the current instant; past and future calendar views use midnight. */
export function bookedStayCutoffForDay(start: Date, end: Date, now = new Date()): Date {
  return start <= now && now < end ? now : start;
}

/** Finds a stay that still holds its bed after `from`, excluding an edit target. */
export function findOverlappingStay<T extends HeldStayWindow>(stays: T[], from: Date, ignoreId?: string, now = new Date()): T | undefined {
  return stays.find((stay) => stay.id !== ignoreId && heldUntil(stay, now) > from);
}
