defmodule Microwaveprop.Weather.NarrProfile do
  @moduledoc """
  Profile rows fetched from NCEP NARR (North American Regional Reanalysis)
  for pre-2014 contacts where the HRRR archive doesn't reach.

  The table was originally created as `era5_profiles` for the retired
  ERA5/CDS pipeline and reused 1:1 by NARR; the
  `rename_era5_profiles_to_narr_profiles` migration renames it to
  `narr_profiles`.
  """
  use Ecto.Schema

  import Ecto.Changeset

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

  schema "narr_profiles" do
    field :valid_time, :utc_datetime
    field :lat, :float
    field :lon, :float
    field :profile, {:array, :map}
    field :hpbl_m, :float
    field :pwat_mm, :float
    field :surface_temp_c, :float
    field :surface_dewpoint_c, :float
    field :surface_pressure_mb, :float
    field :surface_refractivity, :float
    field :min_refractivity_gradient, :float
    field :ducting_detected, :boolean, default: false
    field :duct_characteristics, {:array, :map}

    timestamps(type: :utc_datetime)
  end

  @type t :: %__MODULE__{}

  @required_fields ~w(valid_time lat lon)a
  @optional_fields ~w(profile hpbl_m pwat_mm surface_temp_c surface_dewpoint_c surface_pressure_mb surface_refractivity min_refractivity_gradient ducting_detected duct_characteristics)a

  @spec changeset(t() | Ecto.Changeset.t(), map()) :: Ecto.Changeset.t()
  def changeset(profile, attrs) do
    profile
    |> cast(attrs, @required_fields ++ @optional_fields)
    |> validate_required(@required_fields)
    |> unique_constraint([:lat, :lon, :valid_time])
  end
end
