using EntKube.Clusters.Domain;
using EntKube.Clusters.Features.RegisterCluster;
using EntKube.Clusters.Infrastructure;
using EntKube.SharedKernel.Domain;
using FluentAssertions;

namespace EntKube.Clusters.Tests.Features;

public class RegisterClusterHandlerTests
{
    private readonly RegisterClusterHandler handler;
    private readonly InMemoryClusterRepository repository;

    public RegisterClusterHandlerTests()
    {
        repository = new InMemoryClusterRepository();
        handler = new RegisterClusterHandler(repository);
    }

    [Fact]
    public async Task HandleAsync_WithValidRequest_ReturnsSuccessWithClusterId()
    {
        // Arrange — A valid registration request with all required fields.

        RegisterClusterRequest request = new("production-eu", "https://k8s.example.com:6443", "secret-ref");

        // Act

        Result<Guid> result = await handler.HandleAsync(request);

        // Assert — The handler should succeed and the cluster should be persisted.

        result.IsSuccess.Should().BeTrue();
        result.Value.Should().NotBe(Guid.Empty);

        KubernetesCluster? persisted = await repository.GetByIdAsync(result.Value!);
        persisted.Should().NotBeNull();
        persisted!.Name.Should().Be("production-eu");
    }

    [Fact]
    public async Task HandleAsync_WithEmptyName_ReturnsFailure()
    {
        // Arrange — Missing cluster name.

        RegisterClusterRequest request = new("", "https://k8s.example.com:6443", null);

        // Act

        Result<Guid> result = await handler.HandleAsync(request);

        // Assert

        result.IsFailure.Should().BeTrue();
        result.Error.Should().Contain("name");
    }

    [Fact]
    public async Task HandleAsync_WithEmptyApiUrl_ReturnsFailure()
    {
        // Arrange — Missing API server URL.

        RegisterClusterRequest request = new("my-cluster", "", null);

        // Act

        Result<Guid> result = await handler.HandleAsync(request);

        // Assert

        result.IsFailure.Should().BeTrue();
        result.Error.Should().Contain("API server URL");
    }
}
