CREATE TABLE IF NOT EXISTS complex_plan_run (
    id BIGSERIAL PRIMARY KEY,
    status VARCHAR(20) NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    started_at TIMESTAMP,
    finished_at TIMESTAMP,
    duration_ms BIGINT,
    interval_start TIMESTAMP NOT NULL,
    interval_end TIMESTAMP NOT NULL,
    requested_by VARCHAR(255),
    error_message TEXT,
    calculated_modes_count INTEGER NOT NULL DEFAULT 0,
    booked_modes_count INTEGER NOT NULL DEFAULT 0,
    complan_modes_count INTEGER NOT NULL DEFAULT 0,
    mixed_modes_count INTEGER NOT NULL DEFAULT 0,
    affected_satellites_count INTEGER NOT NULL DEFAULT 0,
    processed_cells_count INTEGER NOT NULL DEFAULT 0,
    booked_slot_links_count INTEGER NOT NULL DEFAULT 0,
    request_payload TEXT,
    CONSTRAINT chk_complex_plan_run_status CHECK (status IN ('CREATED', 'RUNNING', 'COMPLETED', 'FAILED'))
);

CREATE INDEX IF NOT EXISTS idx_complex_plan_run_status
    ON complex_plan_run(status);

CREATE INDEX IF NOT EXISTS idx_complex_plan_run_created_at
    ON complex_plan_run(created_at);

CREATE INDEX IF NOT EXISTS idx_complex_plan_run_interval_start
    ON complex_plan_run(interval_start);

CREATE INDEX IF NOT EXISTS idx_complex_plan_run_interval_end
    ON complex_plan_run(interval_end);

CREATE TABLE IF NOT EXISTS complex_plan_run_satellite (
    id BIGSERIAL PRIMARY KEY,
    run_id BIGINT NOT NULL REFERENCES complex_plan_run(id) ON DELETE CASCADE,
    satellite_id BIGINT NOT NULL,
    CONSTRAINT uq_complex_plan_run_satellite_run_satellite UNIQUE (run_id, satellite_id)
);

CREATE INDEX IF NOT EXISTS idx_complex_plan_run_satellite_run_id
    ON complex_plan_run_satellite(run_id);

CREATE INDEX IF NOT EXISTS idx_complex_plan_run_satellite_satellite_id
    ON complex_plan_run_satellite(satellite_id);

ALTER TABLE satellite_modes
    ADD COLUMN IF NOT EXISTS complex_plan_run_id BIGINT REFERENCES complex_plan_run(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_satellite_modes_complex_plan_run_id
    ON satellite_modes(complex_plan_run_id);
