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

  def change do
    alter table(:qsos) do
      add :hrrr_status, :string, default: "pending", null: false
      add :weather_status, :string, default: "pending", null: false
      add :terrain_status, :string, default: "pending", null: false
      add :iemre_status, :string, default: "pending", null: false
    end

    flush()

    # Backfill: queued=true → complete, queued=false → pending
    execute(
      "UPDATE qsos SET hrrr_status = CASE WHEN hrrr_queued THEN 'complete' ELSE 'pending' END",
      "SELECT 1"
    )

    execute(
      "UPDATE qsos SET weather_status = CASE WHEN weather_queued THEN 'complete' ELSE 'pending' END",
      "SELECT 1"
    )

    execute(
      "UPDATE qsos SET terrain_status = CASE WHEN terrain_queued THEN 'complete' ELSE 'pending' END",
      "SELECT 1"
    )

    execute(
      "UPDATE qsos SET iemre_status = CASE WHEN iemre_queued THEN 'complete' ELSE 'pending' END",
      "SELECT 1"
    )

    # Drop old boolean columns and their partial indexes
    drop_if_exists index(:qsos, [:weather_queued], name: :qsos_weather_queued_index)
    drop_if_exists index(:qsos, [:hrrr_queued], name: :qsos_hrrr_queued_index)
    drop_if_exists index(:qsos, [:terrain_queued], name: :qsos_terrain_queued_index)
    drop_if_exists index(:qsos, [:iemre_queued], name: :qsos_iemre_queued_index)

    alter table(:qsos) do
      remove :weather_queued, :boolean, default: false
      remove :hrrr_queued, :boolean, default: false
      remove :terrain_queued, :boolean, default: false
      remove :iemre_queued, :boolean, default: false
    end

    # Partial indexes for finding contacts needing enrichment
    create index(:qsos, [:hrrr_status],
             where: "hrrr_status != 'complete'",
             name: :qsos_hrrr_status_pending_index
           )

    create index(:qsos, [:weather_status],
             where: "weather_status != 'complete'",
             name: :qsos_weather_status_pending_index
           )

    create index(:qsos, [:terrain_status],
             where: "terrain_status != 'complete'",
             name: :qsos_terrain_status_pending_index
           )

    create index(:qsos, [:iemre_status],
             where: "iemre_status != 'complete'",
             name: :qsos_iemre_status_pending_index
           )
  end
end
