"""Availability helpers for Turfslot."""

from __future__ import annotations

from typing import Iterable

from .exceptions import CourtNotAvailableError
from .models import SportSlot


class SportAvailabilityChecker:
    """Checks if a requested slot is free given existing bookings."""

    def check_availability(self, slot: SportSlot, existing_bookings: Iterable[SportSlot]) -> None:
        for existing in existing_bookings or []:
            if existing.court_id != slot.court_id:
                continue
            if existing.sport_type != slot.sport_type:
                continue
            if self._slots_overlap(slot, existing):
                raise CourtNotAvailableError(
                    f"Court {slot.court_id} is not available between {slot.start_time} and {slot.end_time}."
                )

    @staticmethod
    def _slots_overlap(a: SportSlot, b: SportSlot) -> bool:
        return a.start_time < b.end_time and a.end_time > b.start_time
