defmodule Towerops.Preseem.SubscriberMetricTest do
  use Towerops.DataCase, async: true

  import Towerops.AccountsFixtures
  import Towerops.OrganizationsFixtures

  alias Towerops.Preseem.AccessPoint
  alias Towerops.Preseem.SubscriberMetric

  setup do
    user = user_fixture()
    org = organization_fixture(user.id)

    {:ok, ap} =
      %AccessPoint{}
      |> AccessPoint.changeset(%{organization_id: org.id, preseem_id: "ap-1", name: "Test AP"})
      |> Repo.insert()

    %{access_point: ap}
  end

  describe "changeset/2" do
    test "valid changeset", %{access_point: ap} do
      attrs = %{
        preseem_access_point_id: ap.id,
        avg_latency: 12.5,
        avg_jitter: 3.2,
        avg_loss: 0.5,
        avg_throughput: 45.8,
        p95_latency: 28.3,
        subscriber_count: 42,
        recorded_at: DateTime.truncate(DateTime.utc_now(), :second)
      }

      changeset = SubscriberMetric.changeset(%SubscriberMetric{}, attrs)
      assert changeset.valid?
    end

    test "requires preseem_access_point_id" do
      attrs = %{recorded_at: DateTime.truncate(DateTime.utc_now(), :second)}
      changeset = SubscriberMetric.changeset(%SubscriberMetric{}, attrs)
      refute changeset.valid?
      assert "can't be blank" in errors_on(changeset).preseem_access_point_id
    end

    test "requires recorded_at" do
      attrs = %{preseem_access_point_id: Ecto.UUID.generate()}
      changeset = SubscriberMetric.changeset(%SubscriberMetric{}, attrs)
      refute changeset.valid?
      assert "can't be blank" in errors_on(changeset).recorded_at
    end

    test "persists and reloads metrics", %{access_point: ap} do
      attrs = %{
        preseem_access_point_id: ap.id,
        avg_latency: 12.5,
        p95_latency: 28.3,
        subscriber_count: 42,
        recorded_at: DateTime.truncate(DateTime.utc_now(), :second)
      }

      {:ok, metric} = %SubscriberMetric{} |> SubscriberMetric.changeset(attrs) |> Repo.insert()
      reloaded = Repo.get!(SubscriberMetric, metric.id)
      assert reloaded.avg_latency == 12.5
      assert reloaded.p95_latency == 28.3
      assert reloaded.subscriber_count == 42
    end
  end
end
