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

namespace SIGCM2.Application.IngresosBrutos.Reactivate;

public sealed class ReactivateIngresosBrutosCommandHandler
    : ICommandHandler<ReactivateIngresosBrutosCommand, IngresosBrutosDto>
{
    private readonly IIngresosBrutosRepository _repo;
    private readonly IAuditLogger _audit;
    private readonly TimeProvider _timeProvider;

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

    public async Task<IngresosBrutosDto> Handle(ReactivateIngresosBrutosCommand command)
    {
        var entity = await _repo.GetByIdAsync(command.Id)
            ?? throw new IngresosBrutosNotFoundException(command.Id);

        if (entity.Activo)
            return IngresosBrutosMapper.ToDto(entity);

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

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

        await _audit.LogAsync(
            action: "ingresos_brutos.reactivate",
            targetType: "IngresosBrutos",
            targetId: command.Id.ToString());

        tx.Complete();

        var now = _timeProvider.GetUtcNow().UtcDateTime;
        return IngresosBrutosMapper.ToDto(entity.Reactivate(now));
    }
}
