-- +goose Up
-- Legacy/manual migration kept for reference. Canonical goose migration:
-- migrations/goose/20260613_base_operational_shift_times_date_range.sql

ALTER TABLE base_operational_shift_times
  ADD COLUMN IF NOT EXISTS date_start DATE NULL AFTER base_id,
  ADD COLUMN IF NOT EXISTS date_end DATE NULL AFTER date_start;

UPDATE base_operational_shift_times
SET date_start = COALESCE(date_start, operation_date),
    date_end = COALESCE(date_end, operation_date)
WHERE deleted_at IS NULL;

ALTER TABLE base_operational_shift_times
  DROP FOREIGN KEY fk_base_operational_shift_times_base;

ALTER TABLE base_operational_shift_times
  DROP INDEX idx_base_operational_shift_times_base_date;

ALTER TABLE base_operational_shift_times
  DROP COLUMN operation_date;

ALTER TABLE base_operational_shift_times
  ADD KEY idx_base_operational_shift_times_base_date (base_id, date_start, date_end),
  MODIFY COLUMN date_start DATE NULL,
  MODIFY COLUMN date_end DATE NULL,
  ADD CONSTRAINT fk_base_operational_shift_times_base
    FOREIGN KEY (base_id) REFERENCES bases(id)
    ON UPDATE CASCADE
    ON DELETE CASCADE;

-- +goose Down
ALTER TABLE base_operational_shift_times
  ADD COLUMN IF NOT EXISTS operation_date DATE NULL AFTER base_id;

UPDATE base_operational_shift_times
SET operation_date = COALESCE(operation_date, date_start)
WHERE deleted_at IS NULL;

ALTER TABLE base_operational_shift_times
  DROP FOREIGN KEY fk_base_operational_shift_times_base;

ALTER TABLE base_operational_shift_times
  DROP INDEX idx_base_operational_shift_times_base_date;

ALTER TABLE base_operational_shift_times
  ADD KEY idx_base_operational_shift_times_base_date (base_id, operation_date),
  DROP COLUMN date_start,
  DROP COLUMN date_end,
  MODIFY COLUMN operation_date DATE NOT NULL,
  ADD CONSTRAINT fk_base_operational_shift_times_base
    FOREIGN KEY (base_id) REFERENCES bases(id)
    ON UPDATE CASCADE
    ON DELETE CASCADE;
