defmodule Towerops.Monitoring.MonitoringCheck do
  @moduledoc """
  Schema for the `monitoring_checks` table.

  Stores ping/monitoring check results from agents and the Phoenix server.
  Each record captures the device status, response time, and which agent
  performed the check.
  """
  use Ecto.Schema

  import Ecto.Changeset

  alias Towerops.Agents.AgentToken
  alias Towerops.Devices.Device

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

  schema "monitoring_checks" do
    field :status, :string
    field :response_time_ms, :float
    field :checked_at, :utc_datetime

    belongs_to :device, Device
    belongs_to :agent_token, AgentToken

    timestamps(type: :utc_datetime, updated_at: false)
  end

  def changeset(monitoring_check, attrs) do
    monitoring_check
    |> cast(attrs, [:device_id, :agent_token_id, :status, :response_time_ms, :checked_at])
    |> validate_required([:device_id, :status, :checked_at])
    |> foreign_key_constraint(:device_id)
    |> foreign_key_constraint(:agent_token_id)
  end
end
