-- 009_booking_window_hour_only.sql
-- Ventana diaria de reserva por tipo + solo modo hora.
--   booking_window_start / booking_window_end → rango horario local permitido (TIME)
-- Migra tipos en modo "day" a hour y slot_size half_day/full_day → 1h (duración mínima razonable).
-- Restringe slot_size a valores por hora.

ALTER TABLE resource_types
  ADD COLUMN IF NOT EXISTS booking_window_start time NOT NULL DEFAULT TIME '08:00:00',
  ADD COLUMN IF NOT EXISTS booking_window_end time NOT NULL DEFAULT TIME '20:00:00';

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'resource_types_booking_window_check'
  ) THEN
    ALTER TABLE resource_types ADD CONSTRAINT resource_types_booking_window_check
      CHECK (booking_window_end > booking_window_start);
  END IF;
END$$;

UPDATE resource_types
SET booking_unit = 'hour'
WHERE booking_unit IS DISTINCT FROM 'hour';

-- Antes de endurecer CHECK: normalizar valores legacy de modo día
UPDATE resource_types
SET slot_size = '1h'
WHERE slot_size IN ('half_day', 'full_day');

ALTER TABLE resource_types DROP CONSTRAINT IF EXISTS resource_types_slot_size_check;

ALTER TABLE resource_types ADD CONSTRAINT resource_types_slot_size_check
  CHECK (slot_size IN ('15min', '30min', '1h'));

COMMENT ON COLUMN resource_types.booking_unit IS
  'Siempre hour (reserva por franjas dentro de la ventana diaria).';

COMMENT ON COLUMN resource_types.booking_window_start IS
  'Hora local de inicio del intervalo en el que se pueden iniciar reservas ese día.';

COMMENT ON COLUMN resource_types.booking_window_end IS
  'Hora local de fin del intervalo de reserva (las reservas deben terminar a esta hora o antes).';

COMMENT ON COLUMN resource_types.slot_size IS
  'Duración mínima de reserva: 15min | 30min | 1h.';

COMMENT ON COLUMN resource_types.time_granularity IS
  'Paso de la grilla / incrementos de hora inicio y duración: 5min | 10min | 15min | 30min';
