ALTER TABLE `image_generations`
  ADD COLUMN `archive_status` ENUM('NOT_REQUIRED', 'PENDING', 'RUNNING', 'SUCCEEDED', 'FAILED') NOT NULL DEFAULT 'NOT_REQUIRED',
  ADD COLUMN `archive_attempts` INT NOT NULL DEFAULT 0,
  ADD COLUMN `archive_next_run_at` DATETIME(3) NULL,
  ADD COLUMN `archive_locked_at` DATETIME(3) NULL,
  ADD COLUMN `archive_locked_by` VARCHAR(191) NULL,
  ADD COLUMN `archive_last_error` TEXT NULL;

UPDATE `image_generations`
SET `archive_status` = 'SUCCEEDED'
WHERE `status` = 'SUCCEEDED'
  AND `hosted_image_url` IS NOT NULL;

UPDATE `image_generations`
SET
  `archive_status` = 'PENDING',
  `archive_next_run_at` = CURRENT_TIMESTAMP(3)
WHERE `status` = 'SUCCEEDED'
  AND `hosted_image_url` IS NULL
  AND `error_message` IS NULL
  AND `image_url` IS NOT NULL;

UPDATE `image_generations`
SET `archive_status` = 'FAILED'
WHERE `status` = 'SUCCEEDED'
  AND `hosted_image_url` IS NULL
  AND `error_message` IS NOT NULL;

CREATE INDEX `image_generations_archive_status_archive_next_run_at_idx`
  ON `image_generations`(`archive_status`, `archive_next_run_at`);

CREATE INDEX `image_generations_archive_locked_at_idx`
  ON `image_generations`(`archive_locked_at`);
