-- =====================================================
-- Instructor Availability Check
--
-- Returns TRUE if the instructor has no scheduling
-- conflicts for the requested date/time window.
-- Optionally excludes a specific session (for edits).
-- =====================================================

CREATE OR REPLACE FUNCTION public.check_instructor_availability(
  p_instructor_id uuid,
  p_session_date date,
  p_start_time time,
  p_end_time time,
  p_exclude_session_id uuid DEFAULT NULL
)
RETURNS boolean
LANGUAGE sql
STABLE
SECURITY DEFINER
SET search_path = ''
AS $$
  SELECT NOT EXISTS (
    SELECT 1
    FROM public.course_sessions cs
    JOIN public.courses c ON c.id = cs.course_id
    WHERE c.instructor_id = p_instructor_id
      AND cs.session_date = p_session_date
      AND cs.start_time < p_end_time
      AND cs.end_time > p_start_time
      AND (p_exclude_session_id IS NULL OR cs.id != p_exclude_session_id)
      AND cs.is_cancelled = false
  );
$$;

GRANT EXECUTE ON FUNCTION public.check_instructor_availability(uuid, date, time, time, uuid) TO authenticated;
GRANT EXECUTE ON FUNCTION public.check_instructor_availability(uuid, date, time, time, uuid) TO service_role;
