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

  def change do
    create table(:rover_missions, primary_key: false) do
      add :id, :binary_id, primary_key: true, null: false
      add :user_id, references(:users, type: :binary_id, on_delete: :nilify_all), null: false
      add :name, :string, null: false
      add :band_mhz, :integer, null: false, default: 10_000
      add :only_known_good, :boolean, null: false, default: true
      add :rover_height_ft, :float, null: false, default: 8.0
      add :station_height_ft, :float, null: false, default: 30.0
      add :notes, :text
      timestamps(type: :utc_datetime)
    end

    create index(:rover_missions, [:user_id])
    create index(:rover_missions, [:inserted_at])

    create table(:rover_mission_stations, primary_key: false) do
      add :id, :binary_id, primary_key: true, null: false

      add :mission_id, references(:rover_missions, type: :binary_id, on_delete: :delete_all),
        null: false

      add :callsign, :string
      add :grid, :string
      add :input, :string, null: false
      add :lat, :float, null: false
      add :lon, :float, null: false
      add :position, :integer, null: false, default: 0
      timestamps(type: :utc_datetime)
    end

    create index(:rover_mission_stations, [:mission_id])

    create table(:rover_mission_paths, primary_key: false) do
      add :id, :binary_id, primary_key: true, null: false

      add :mission_id, references(:rover_missions, type: :binary_id, on_delete: :delete_all),
        null: false

      add :rover_location_id,
          references(:rover_locations, type: :binary_id, on_delete: :delete_all),
          null: false

      add :station_id,
          references(:rover_mission_stations, type: :binary_id, on_delete: :delete_all),
          null: false

      add :status, :string, null: false, default: "pending"
      add :result, :map
      add :error, :text
      add :computed_at, :utc_datetime
      timestamps(type: :utc_datetime)
    end

    create index(:rover_mission_paths, [:mission_id])
    create index(:rover_mission_paths, [:status])

    create unique_index(:rover_mission_paths, [:mission_id, :rover_location_id, :station_id],
             name: :rover_mission_paths_unique
           )
  end
end
