defmodule Microwaveprop.Radio.ContactCommonVolumeRadar do
  @moduledoc """
  Aggregated n0q composite reflectivity statistics sampled inside the
  common volume (lens-shaped intersection of two 400 km circles around
  the endpoints) for a single contact, at the QSO time.

  One row per contact. Feeds `Microwaveprop.Propagation.RainScatterClassifier`.
  """
  use Ecto.Schema

  import Ecto.Changeset

  alias Microwaveprop.Radio.Contact

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

  schema "contact_common_volume_radar" do
    belongs_to :contact, Contact

    field :observed_at, :utc_datetime
    field :common_volume_km2, :float
    field :pixel_count, :integer, default: 0
    field :rain_pixel_count, :integer, default: 0
    field :heavy_rain_pixel_count, :integer, default: 0
    field :core_pixel_count, :integer, default: 0
    field :max_dbz, :float
    field :mean_dbz, :float
    field :coverage_pct, :float

    timestamps(type: :utc_datetime)
  end

  @type t :: %__MODULE__{}

  @required ~w(contact_id observed_at)a
  @optional ~w(common_volume_km2 pixel_count rain_pixel_count heavy_rain_pixel_count
               core_pixel_count max_dbz mean_dbz coverage_pct)a

  @spec changeset(t() | Ecto.Changeset.t(), map()) :: Ecto.Changeset.t()
  def changeset(row, attrs) do
    row
    |> cast(attrs, @required ++ @optional)
    |> validate_required(@required)
    |> unique_constraint(:contact_id)
  end
end
