defmodule Towerops.Monitoring.CheckResult do
  @moduledoc """
  Stores results from check executions in TimescaleDB hypertable.

  Results are time-series data showing check status over time.
  """
  use Ecto.Schema

  import Ecto.Changeset

  alias Towerops.Agents.AgentToken
  alias Towerops.Monitoring.Check
  alias Towerops.Organizations.Organization

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

  schema "check_results" do
    field :checked_at, :utc_datetime
    field :status, :integer
    field :output, :string
    field :value, :float
    field :response_time_ms, :float

    belongs_to :organization, Organization
    belongs_to :check, Check
    belongs_to :agent_token, AgentToken
  end

  def changeset(result, attrs) do
    result
    |> cast(attrs, [
      :checked_at,
      :status,
      :output,
      :value,
      :response_time_ms,
      :organization_id,
      :check_id,
      :agent_token_id
    ])
    |> validate_required([:checked_at, :status, :organization_id, :check_id])
    |> validate_inclusion(:status, 0..3)
    |> foreign_key_constraint(:organization_id)
    |> foreign_key_constraint(:check_id)
    |> foreign_key_constraint(:agent_token_id)
  end
end
