defmodule Microwaveprop.Weather.Sounding do
  @moduledoc false
  use Ecto.Schema

  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id

  schema "soundings" do
    belongs_to :station, Microwaveprop.Weather.Station
    field :observed_at, :utc_datetime
    field :profile, {:array, :map}
    field :level_count, :integer
    field :surface_pressure_mb, :float
    field :surface_temp_c, :float
    field :surface_dewpoint_c, :float
    field :surface_refractivity, :float
    field :min_refractivity_gradient, :float
    field :boundary_layer_depth_m, :float
    field :precipitable_water_mm, :float
    field :k_index, :float
    field :lifted_index, :float
    field :ducting_detected, :boolean, default: false
    field :duct_characteristics, {:array, :map}

    timestamps(type: :utc_datetime)
  end

  @type t :: %__MODULE__{}

  @required_fields ~w(station_id observed_at profile level_count)a
  @optional_fields ~w(surface_pressure_mb surface_temp_c surface_dewpoint_c surface_refractivity min_refractivity_gradient boundary_layer_depth_m precipitable_water_mm k_index lifted_index ducting_detected duct_characteristics)a

  @spec changeset(t() | Ecto.Changeset.t(), map()) :: Ecto.Changeset.t()
  def changeset(sounding, attrs) do
    sounding
    |> cast(attrs, @required_fields ++ @optional_fields)
    |> validate_required(@required_fields)
    |> foreign_key_constraint(:station_id)
    |> unique_constraint([:station_id, :observed_at])
  end
end
