-- migrate:up

-- Agregar columna schedule JSONB para horarios flexibles por día
-- Estructura: { "delivery": { "lun": { "start": "09:00", "end": "14:00" }, ... }, "pickup": { ... } }
ALTER TABLE tenant_settings
ADD COLUMN IF NOT EXISTS schedule JSONB DEFAULT '{}';

-- Migrar datos existentes al nuevo formato
UPDATE tenant_settings
SET schedule = jsonb_build_object(
  'delivery', CASE 
    WHEN delivery_enabled AND delivery_days IS NOT NULL THEN (
      SELECT jsonb_object_agg(
        day,
        jsonb_build_object(
          'start', COALESCE(delivery_hours_start::text, '09:00'),
          'end', COALESCE(delivery_hours_end::text, '18:00')
        )
      )
      FROM unnest(string_to_array(delivery_days, ',')) AS day
      WHERE day IS NOT NULL AND day != ''
    )
    ELSE '{}'::jsonb
  END,
  'pickup', CASE 
    WHEN pickup_enabled AND pickup_days IS NOT NULL THEN (
      SELECT jsonb_object_agg(
        day,
        jsonb_build_object(
          'start', COALESCE(pickup_hours_start::text, '08:00'),
          'end', COALESCE(pickup_hours_end::text, '20:00')
        )
      )
      FROM unnest(string_to_array(pickup_days, ',')) AS day
      WHERE day IS NOT NULL AND day != ''
    )
    ELSE '{}'::jsonb
  END
)
WHERE schedule = '{}' OR schedule IS NULL;

-- migrate:down

ALTER TABLE tenant_settings DROP COLUMN IF EXISTS schedule;
