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

  import Ecto.Changeset

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

  schema "surface_observations" do
    belongs_to :station, Microwaveprop.Weather.Station
    field :observed_at, :utc_datetime
    field :temp_f, :float
    field :dewpoint_f, :float
    field :relative_humidity, :float
    field :wind_speed_kts, :float
    field :wind_direction_deg, :integer
    field :sea_level_pressure_mb, :float
    field :altimeter_setting, :float
    field :sky_condition, :string
    field :precip_1h_in, :float
    field :wx_codes, :string

    timestamps(type: :utc_datetime)
  end

  @type t :: %__MODULE__{}

  @required_fields ~w(station_id observed_at)a
  @optional_fields ~w(temp_f dewpoint_f relative_humidity wind_speed_kts wind_direction_deg sea_level_pressure_mb altimeter_setting sky_condition precip_1h_in wx_codes)a

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