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 CreateOrganizationCommandHandler.
/// VI: Unit tests cho CreateOrganizationCommandHandler.
/// </summary>
public class CreateOrganizationCommandHandlerTests
{
    private readonly Mock<IOrganizationRepository> _organizationRepositoryMock;
    private readonly Mock<ILogger<CreateOrganizationCommandHandler>> _loggerMock;
    private readonly Mock<IUnitOfWork> _unitOfWorkMock;
    private readonly CreateOrganizationCommandHandler _handler;

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

        // EN: Setup UnitOfWork mock
        // VI: Thiết lập mock cho UnitOfWork
        _unitOfWorkMock
            .Setup(u => u.SaveEntitiesAsync(It.IsAny<CancellationToken>()))
            .ReturnsAsync(true);
        _organizationRepositoryMock
            .Setup(r => r.UnitOfWork)
            .Returns(_unitOfWorkMock.Object);

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

    [Fact]
    public async Task Handle_ValidCommand_CreatesOrganizationAndReturnsResult()
    {
        // Arrange
        var command = new CreateOrganizationCommand(
            Name: "Acme Corporation",
            Slug: "acme-corp",
            Description: "A sample organization");

        _organizationRepositoryMock
            .Setup(r => r.IsSlugUniqueAsync(command.Slug, null, It.IsAny<CancellationToken>()))
            .ReturnsAsync(true);

        Organization? capturedOrg = null;
        _organizationRepositoryMock
            .Setup(r => r.Add(It.IsAny<Organization>()))
            .Callback<Organization>(o => capturedOrg = o)
            .Returns((Organization o) => o);

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

        // Assert
        result.Should().NotBeNull();
        result.Id.Should().NotBeEmpty();
        result.Name.Should().Be("Acme Corporation");
        result.Slug.Should().Be("acme-corp");
        result.Description.Should().Be("A sample organization");
        result.Status.Should().Be("Active");
        result.ParentOrganizationId.Should().BeNull();
        result.CreatedAt.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(1));

        capturedOrg.Should().NotBeNull();
    }

    [Fact]
    public async Task Handle_ValidCommand_PersistsOrganizationToRepository()
    {
        // Arrange
        var command = new CreateOrganizationCommand("Test Org", "test-org");

        _organizationRepositoryMock
            .Setup(r => r.IsSlugUniqueAsync(command.Slug, null, It.IsAny<CancellationToken>()))
            .ReturnsAsync(true);

        _organizationRepositoryMock
            .Setup(r => r.Add(It.IsAny<Organization>()))
            .Returns((Organization o) => o);

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

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

    [Fact]
    public async Task Handle_DuplicateSlug_ThrowsDomainException()
    {
        // Arrange
        var command = new CreateOrganizationCommand("Test Org", "existing-slug");

        _organizationRepositoryMock
            .Setup(r => r.IsSlugUniqueAsync(command.Slug, null, It.IsAny<CancellationToken>()))
            .ReturnsAsync(false);

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

        // Assert
        await act.Should().ThrowAsync<DomainException>()
            .WithMessage("*slug*already exists*");

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

    [Fact]
    public async Task Handle_WithParentOrganization_SetsParentId()
    {
        // Arrange
        var parentId = Guid.NewGuid();
        var parentOrg = Organization.Create("Parent Org", "parent-org");
        
        var command = new CreateOrganizationCommand(
            Name: "Child Org",
            Slug: "child-org",
            ParentOrganizationId: parentId);

        _organizationRepositoryMock
            .Setup(r => r.IsSlugUniqueAsync(command.Slug, null, It.IsAny<CancellationToken>()))
            .ReturnsAsync(true);

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

        _organizationRepositoryMock
            .Setup(r => r.Add(It.IsAny<Organization>()))
            .Returns((Organization o) => o);

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

        // Assert
        result.ParentOrganizationId.Should().Be(parentId);
    }

    [Fact]
    public async Task Handle_ParentOrganizationNotFound_ThrowsDomainException()
    {
        // Arrange
        var nonExistentParentId = Guid.NewGuid();
        var command = new CreateOrganizationCommand(
            Name: "Child Org",
            Slug: "child-org",
            ParentOrganizationId: nonExistentParentId);

        _organizationRepositoryMock
            .Setup(r => r.IsSlugUniqueAsync(command.Slug, null, It.IsAny<CancellationToken>()))
            .ReturnsAsync(true);

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

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

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

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

    [Fact]
    public async Task Handle_WithoutDescription_CreatesOrganizationWithNullDescription()
    {
        // Arrange
        var command = new CreateOrganizationCommand(
            Name: "Test Org",
            Slug: "test-org",
            Description: null);

        _organizationRepositoryMock
            .Setup(r => r.IsSlugUniqueAsync(command.Slug, null, It.IsAny<CancellationToken>()))
            .ReturnsAsync(true);

        _organizationRepositoryMock
            .Setup(r => r.Add(It.IsAny<Organization>()))
            .Returns((Organization o) => o);

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

        // Assert
        result.Description.Should().BeNull();
    }

    [Fact]
    public async Task Handle_CancellationRequested_PropagatesCancellation()
    {
        // Arrange
        var command = new CreateOrganizationCommand("Test Org", "test-org");
        var cts = new CancellationTokenSource();
        cts.Cancel();

        _organizationRepositoryMock
            .Setup(r => r.IsSlugUniqueAsync(It.IsAny<string>(), null, It.IsAny<CancellationToken>()))
            .ThrowsAsync(new OperationCanceledException());

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

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