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

namespace SIGCM2.Application.TiposDeIva.Deactivate;

public sealed class DeactivateTipoDeIvaCommandHandler : ICommandHandler<DeactivateTipoDeIvaCommand, TipoDeIvaDto>
{
    private readonly ITipoDeIvaRepository _repo;
    private readonly IAuditLogger _audit;
    private readonly TimeProvider _timeProvider;

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

    public async Task<TipoDeIvaDto> Handle(DeactivateTipoDeIvaCommand command)
    {
        var entity = await _repo.GetByIdAsync(command.Id)
            ?? throw new TipoDeIvaNotFoundException(command.Id);

        // Idempotent: already inactive → return as-is without writing an audit event
        if (!entity.Activo)
            return TipoDeIvaMapper.ToDto(entity);

        using var tx = new TransactionScope(
            TransactionScopeOption.Required,
            new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted },
            TransactionScopeAsyncFlowOption.Enabled);

        await _repo.SetActivoAsync(command.Id, false);

        await _audit.LogAsync(
            action: "tipo_iva.deactivate",
            targetType: "TipoDeIva",
            targetId: command.Id.ToString());

        tx.Complete();

        var now = _timeProvider.GetUtcNow().UtcDateTime;
        return TipoDeIvaMapper.ToDto(entity.Deactivate(now));
    }
}
