defmodule Towerops.Agents.ReleaseCheckerTest do
  use ExUnit.Case, async: true

  alias Towerops.Agents.ReleaseChecker

  describe "get_latest_release/0" do
    @tag :integration
    test "returns release info with version and assets" do
      {:ok, release} = ReleaseChecker.get_latest_release()

      assert is_binary(release.version)
      assert is_list(release.assets)

      assert Enum.any?(release.assets, fn asset ->
               String.contains?(asset.name, "amd64")
             end)

      assert Enum.any?(release.assets, fn asset ->
               String.contains?(asset.name, "arm64")
             end)
    end
  end

  describe "asset_for_arch/2" do
    test "returns matching asset for x86_64 arch" do
      assets = [
        %{name: "towerops-agent-linux-amd64", url: "https://example.com/amd64", checksum: "abc"},
        %{name: "towerops-agent-linux-arm64", url: "https://example.com/arm64", checksum: "def"}
      ]

      assert {:ok, asset} = ReleaseChecker.asset_for_arch(assets, "x86_64")
      assert asset.name == "towerops-agent-linux-amd64"
    end

    test "returns matching asset for aarch64 arch" do
      assets = [
        %{name: "towerops-agent-linux-amd64", url: "https://example.com/amd64", checksum: "abc"},
        %{name: "towerops-agent-linux-arm64", url: "https://example.com/arm64", checksum: "def"}
      ]

      assert {:ok, asset} = ReleaseChecker.asset_for_arch(assets, "aarch64")
      assert asset.name == "towerops-agent-linux-arm64"
    end

    test "returns error for unknown arch" do
      assets = [
        %{name: "towerops-agent-linux-amd64", url: "https://example.com/amd64", checksum: "abc"}
      ]

      assert {:error, :no_matching_asset} = ReleaseChecker.asset_for_arch(assets, "riscv64")
    end
  end

  describe "invalidate_cache/0" do
    test "returns :ok when no cache exists" do
      # Ensure cache is clear
      try do
        :persistent_term.erase({ReleaseChecker, :release})
      rescue
        ArgumentError -> :ok
      end

      assert :ok = ReleaseChecker.invalidate_cache()
    end

    test "clears existing cache" do
      # Seed the cache
      :persistent_term.put(
        {ReleaseChecker, :release},
        {%{version: "1.0.0", assets: []}, System.monotonic_time(:millisecond)}
      )

      assert :ok = ReleaseChecker.invalidate_cache()

      # Verify cache is gone
      assert :persistent_term.get({ReleaseChecker, :release}, nil) == nil
    end
  end
end
