defmodule Refuge.RemoteCache.RemoteCacheTest do
  use ExUnit.Case, async: false
  
  require Logger
  alias Refuge.RemoteCache.DiskStore

  @moduledoc """
  Integration tests for the Bazel Remote Execution API implementation.
  These tests verify that our server correctly handles requests
  for the ContentAddressableStorage and ActionCache services.
  """
  
  setup do
    # Use a test-specific cache directory
    cache_dir = "priv/test_bazel_cache_#{System.unique_integer([:positive])}"
    
    # Start a clean DiskStore for this test
    start_supervised!({Refuge.RemoteCache.DiskStore, [cache_dir: cache_dir]})
    
    # Cleanup after test
    on_exit fn ->
      File.rm_rf!(cache_dir)
    end
    
    %{cache_dir: cache_dir}
  end

  test "store and retrieve CAS blobs" do
    # Simple blob data for testing
    hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"  # SHA-256 of empty string
    data = ""
    
    # Store blob
    assert :ok = DiskStore.store_cas_blob(hash, data)
    
    # Retrieve blob
    assert {:ok, ^data} = DiskStore.get_cas_blob(hash)
  end

  test "find missing CAS blobs" do
    # Store one blob
    hash1 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
    data1 = ""
    assert :ok = DiskStore.store_cas_blob(hash1, data1)
    
    # Define another hash that we won't store
    hash2 = "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"  # SHA-256 of "hello world"
    
    # Find missing blobs
    missing = DiskStore.find_missing_cas_blobs([hash1, hash2])
    assert length(missing) == 1
    assert Enum.at(missing, 0) == hash2
  end

  test "store and retrieve action results" do
    # Example action result hash and data
    hash = "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"
    data = "example action result data"
    
    # Store action result
    assert :ok = DiskStore.store_action_result(hash, data)
    
    # Retrieve action result
    assert {:ok, ^data} = DiskStore.get_action_result(hash)
  end

  test "action result not found" do
    # Hash that shouldn't exist in the cache
    hash = "nonexistent123456789abcdef"
    
    # Try to retrieve a non-existent action result
    assert {:error, :not_found} = DiskStore.get_action_result(hash)
  end
end
