using System.Transactions;
using SIGCM2.Application.Abstractions;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Audit;
using SIGCM2.Domain.Entities;
using SIGCM2.Domain.Exceptions;

namespace SIGCM2.Application.ProductTypes.Deactivate;

public sealed class DeactivateProductTypeCommandHandler
    : ICommandHandler<DeactivateProductTypeCommand, ProductTypeStatusDto>
{
    private readonly IProductTypeRepository _repo;
    private readonly IProductQueryRepository _productQuery;
    private readonly IAuditLogger _audit;
    private readonly TimeProvider _timeProvider;

    public DeactivateProductTypeCommandHandler(
        IProductTypeRepository repo,
        IProductQueryRepository productQuery,
        IAuditLogger audit,
        TimeProvider timeProvider)
    {
        _repo = repo;
        _productQuery = productQuery;
        _audit = audit;
        _timeProvider = timeProvider;
    }

    public async Task<ProductTypeStatusDto> Handle(DeactivateProductTypeCommand command)
    {
        // 1. Load entity
        var target = await _repo.GetByIdAsync(command.Id)
            ?? throw new ProductTypeNotFoundException(command.Id);

        // 2. Idempotent: already inactive → return without side effects (I7)
        if (!target.IsActive)
            return new ProductTypeStatusDto(command.Id, false);

        // 3. Guard: check if any active product uses this type
        var inUse = await _productQuery.ExistsActiveByProductTypeAsync(command.Id);
        if (inUse)
            throw new ProductTypeEnUsoException(command.Id, productsActivos: 1);

        // 4. Deactivate (immutable — returns new instance)
        var deactivated = target.WithDeactivated(_timeProvider);

        // 5. Persist + audit (fail-closed)
        using var tx = new TransactionScope(
            TransactionScopeOption.Required,
            new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted },
            TransactionScopeAsyncFlowOption.Enabled);

        await _repo.UpdateAsync(deactivated);

        await _audit.LogAsync(
            action: "producto_tipo.deactivated",
            targetType: "ProductType",
            targetId: command.Id.ToString(),
            metadata: new
            {
                productTypeId = command.Id,
                nombre = target.Nombre,
            });

        tx.Complete();

        return new ProductTypeStatusDto(deactivated.Id, deactivated.IsActive);
    }
}
