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

  def change do
    create table(:hrrr_profiles, primary_key: false) do
      add :id, :binary_id, primary_key: true
      add :valid_time, :utc_datetime, null: false
      add :lat, :float, null: false
      add :lon, :float, null: false
      add :run_time, :utc_datetime
      add :profile, {:array, :map}, default: []
      add :hpbl_m, :float
      add :pwat_mm, :float
      add :surface_temp_c, :float
      add :surface_dewpoint_c, :float
      add :surface_pressure_mb, :float
      add :surface_refractivity, :float
      add :min_refractivity_gradient, :float
      add :ducting_detected, :boolean, default: false
      add :duct_characteristics, {:array, :map}

      timestamps(type: :utc_datetime)
    end

    create unique_index(:hrrr_profiles, [:lat, :lon, :valid_time])
    create index(:hrrr_profiles, [:valid_time])

    alter table(:qsos) do
      add :hrrr_queued, :boolean, default: false, null: false
    end

    # Backfill existing rows to false (need HRRR fetched)
    execute "UPDATE qsos SET hrrr_queued = false", "SELECT 1"

    # Partial index for fast lookup of unprocessed QSOs
    create index(:qsos, [:hrrr_queued], where: "hrrr_queued = false")
  end
end
