using Xunit;
using Moq;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using IamService.API.Application.Commands.Organizations;
using IamService.Domain.AggregatesModel.OrganizationAggregate;
using IamService.Domain.Exceptions;
using IamService.Domain.SeedWork;

namespace IamService.UnitTests.Application.Commands.Organizations;

/// <summary>
/// EN: Unit tests for ArchiveOrganizationCommandHandler.
/// VI: Unit tests cho ArchiveOrganizationCommandHandler.
/// </summary>
public class ArchiveOrganizationCommandHandlerTests
{
    private readonly Mock<IOrganizationRepository> _organizationRepositoryMock;
    private readonly Mock<ILogger<ArchiveOrganizationCommandHandler>> _loggerMock;
    private readonly Mock<IUnitOfWork> _unitOfWorkMock;
    private readonly ArchiveOrganizationCommandHandler _handler;

    public ArchiveOrganizationCommandHandlerTests()
    {
        _organizationRepositoryMock = new Mock<IOrganizationRepository>();
        _loggerMock = new Mock<ILogger<ArchiveOrganizationCommandHandler>>();
        _unitOfWorkMock = new Mock<IUnitOfWork>();

        _unitOfWorkMock
            .Setup(u => u.SaveEntitiesAsync(It.IsAny<CancellationToken>()))
            .ReturnsAsync(true);
        _organizationRepositoryMock
            .Setup(r => r.UnitOfWork)
            .Returns(_unitOfWorkMock.Object);

        _handler = new ArchiveOrganizationCommandHandler(
            _organizationRepositoryMock.Object,
            _loggerMock.Object);
    }

    [Fact]
    public async Task Handle_ValidCommand_ArchivesOrganization()
    {
        // Arrange
        var orgId = Guid.NewGuid();
        var organization = Organization.Create("Test Org", "test-org");
        var command = new ArchiveOrganizationCommand(orgId);

        _organizationRepositoryMock
            .Setup(r => r.GetByIdAsync(orgId, It.IsAny<CancellationToken>()))
            .ReturnsAsync(organization);

        _organizationRepositoryMock
            .Setup(r => r.GetChildrenAsync(orgId, It.IsAny<CancellationToken>()))
            .ReturnsAsync([]);

        // Act
        var result = await _handler.Handle(command, CancellationToken.None);

        // Assert
        result.Should().BeTrue();
        organization.Status.Should().Be(OrganizationStatus.Archived);
    }

    [Fact]
    public async Task Handle_ValidCommand_PersistsChanges()
    {
        // Arrange
        var orgId = Guid.NewGuid();
        var organization = Organization.Create("Test Org", "test-org");
        var command = new ArchiveOrganizationCommand(orgId);

        _organizationRepositoryMock
            .Setup(r => r.GetByIdAsync(orgId, It.IsAny<CancellationToken>()))
            .ReturnsAsync(organization);

        _organizationRepositoryMock
            .Setup(r => r.GetChildrenAsync(orgId, It.IsAny<CancellationToken>()))
            .ReturnsAsync([]);

        // Act
        await _handler.Handle(command, CancellationToken.None);

        // Assert
        _organizationRepositoryMock.Verify(r => r.Update(organization), Times.Once);
        _unitOfWorkMock.Verify(u => u.SaveEntitiesAsync(It.IsAny<CancellationToken>()), Times.Once);
    }

    [Fact]
    public async Task Handle_OrganizationNotFound_ThrowsDomainException()
    {
        // Arrange
        var command = new ArchiveOrganizationCommand(Guid.NewGuid());

        _organizationRepositoryMock
            .Setup(r => r.GetByIdAsync(It.IsAny<Guid>(), It.IsAny<CancellationToken>()))
            .ReturnsAsync((Organization?)null);

        // Act
        var act = async () => await _handler.Handle(command, CancellationToken.None);

        // Assert
        await act.Should().ThrowAsync<DomainException>()
            .WithMessage("*not found*");
    }

    [Fact]
    public async Task Handle_HasChildOrganizations_ThrowsDomainException()
    {
        // Arrange
        var orgId = Guid.NewGuid();
        var organization = Organization.Create("Parent Org", "parent-org");
        var childOrg = Organization.Create("Child Org", "child-org");
        var command = new ArchiveOrganizationCommand(orgId);

        _organizationRepositoryMock
            .Setup(r => r.GetByIdAsync(orgId, It.IsAny<CancellationToken>()))
            .ReturnsAsync(organization);

        _organizationRepositoryMock
            .Setup(r => r.GetChildrenAsync(orgId, It.IsAny<CancellationToken>()))
            .ReturnsAsync([childOrg]);

        // Act
        var act = async () => await _handler.Handle(command, CancellationToken.None);

        // Assert
        await act.Should().ThrowAsync<DomainException>()
            .WithMessage("*child organizations*");

        _organizationRepositoryMock.Verify(r => r.Update(It.IsAny<Organization>()), Times.Never);
    }

    [Fact]
    public async Task Handle_CancellationRequested_PropagatesCancellation()
    {
        // Arrange
        var command = new ArchiveOrganizationCommand(Guid.NewGuid());
        var cts = new CancellationTokenSource();
        cts.Cancel();

        _organizationRepositoryMock
            .Setup(r => r.GetByIdAsync(It.IsAny<Guid>(), It.IsAny<CancellationToken>()))
            .ThrowsAsync(new OperationCanceledException());

        // Act
        var act = async () => await _handler.Handle(command, cts.Token);

        // Assert
        await act.Should().ThrowAsync<OperationCanceledException>();
    }
}
