defmodule Microwaveprop.Repo.Migrations.CreateEra5CdsJobs do
  use Ecto.Migration

  # Tracks in-flight CDS requests for the split Era5SubmitWorker / Era5PollWorker
  # design. A row is created when Era5SubmitWorker successfully submits both
  # CDS jobs, and is deleted when Era5PollWorker downloads the results and
  # inserts profiles (or when either leg permanently fails). Persisting the
  # CDS job IDs lets a pod restart resume polling instead of losing the work.
  def change do
    create table(:era5_cds_jobs, primary_key: false) do
      add :id, :binary_id, primary_key: true
      add :year, :integer, null: false
      add :month, :integer, null: false
      add :tile_lat, :integer, null: false
      add :tile_lon, :integer, null: false
      add :single_job_id, :string, null: false
      add :pressure_job_id, :string, null: false
      add :submitted_at, :utc_datetime, null: false
      add :last_polled_at, :utc_datetime
      add :poll_count, :integer, default: 0, null: false

      timestamps(type: :utc_datetime)
    end

    # Uniqueness so duplicate submits for the same tile-month collapse.
    create unique_index(:era5_cds_jobs, [:year, :month, :tile_lat, :tile_lon])
  end
end
