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.Products.Deactivate;

public sealed class DeactivateProductCommandHandler
    : ICommandHandler<DeactivateProductCommand, ProductStatusDto>
{
    private readonly IProductRepository _repo;
    private readonly IAuditLogger _audit;
    private readonly TimeProvider _timeProvider;

    public DeactivateProductCommandHandler(
        IProductRepository repo,
        IAuditLogger audit,
        TimeProvider timeProvider)
    {
        _repo = repo;
        _audit = audit;
        _timeProvider = timeProvider;
    }

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

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

        // 3. Deactivate (immutable)
        var deactivated = target.WithDeactivated(_timeProvider);

        // 4. 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.deactivated",
            targetType: "Product",
            targetId: command.Id.ToString(),
            metadata: new
            {
                productId = command.Id,
                nombre = target.Nombre,
            });

        tx.Complete();

        return new ProductStatusDto(deactivated.Id, deactivated.IsActive, deactivated.FechaModificacion);
    }
}
