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

  def change do
    create table(:terrain_profiles, primary_key: false) do
      add :id, :binary_id, primary_key: true
      add :qso_id, references(:qsos, type: :binary_id, on_delete: :delete_all), null: false
      add :sample_count, :integer, null: false
      add :path_points, {:array, :map}, default: [], null: false
      add :max_elevation_m, :float
      add :min_clearance_m, :float
      add :diffraction_db, :float
      add :fresnel_hit_count, :integer
      add :obstructed_count, :integer
      add :verdict, :string, null: false

      timestamps(type: :utc_datetime)
    end

    create unique_index(:terrain_profiles, [:qso_id])

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

    execute "UPDATE qsos SET terrain_queued = false", "SELECT 1"

    create index(:qsos, [:terrain_queued], where: "terrain_queued = false")
  end
end
