-- Restore the stored ready flags and the per-job counter.
DROP VIEW IF EXISTS export_current;

ALTER TABLE event ADD COLUMN export_zip_ready  BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE event ADD COLUMN export_html_ready BOOLEAN NOT NULL DEFAULT FALSE;

-- Re-derive the flags from what the epoch model considers downloadable, so the old code sees
-- exactly the state it would have written itself.
UPDATE event e
   SET export_zip_ready = EXISTS (
         SELECT 1 FROM export_job j
          WHERE j.event_id = e.id AND j.type = 'zip'
            AND j.status = 'done' AND j.epoch = e.export_epoch
       ),
       export_html_ready = EXISTS (
         SELECT 1 FROM export_job j
          WHERE j.event_id = e.id AND j.type = 'html'
            AND j.status = 'done' AND j.epoch = e.export_epoch
       )
 WHERE e.export_released_at IS NOT NULL;

ALTER TABLE export_job RENAME COLUMN epoch TO release_seq;

-- The old code treats release_seq as a non-negative per-job counter; the -1 retirement sentinel
-- has no meaning there, so floor it back to 0.
UPDATE export_job SET release_seq = 0 WHERE release_seq < 0;

ALTER TABLE event DROP COLUMN export_epoch;
