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.Update;

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

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

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

        var now = _timeProvider.GetUtcNow().UtcDateTime;
        var updated = entity
            .WithCodigo(command.Codigo, now)
            .WithDescripcion(command.Descripcion, now)
            .WithAplicaIVA(command.AplicaIVA, now);

        // Apply Activo change if needed
        updated = command.Activo
            ? updated.Reactivate(now)
            : updated.Deactivate(now);

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

        await _repo.UpdateCosmeticoAsync(
            command.Id,
            command.Codigo,
            command.Descripcion,
            command.AplicaIVA,
            command.Activo);

        await _audit.LogAsync(
            action: "tipo_iva.update",
            targetType: "TipoDeIva",
            targetId: command.Id.ToString(),
            metadata: new
            {
                before = new { entity.Codigo, entity.Descripcion, entity.AplicaIVA, entity.Activo },
                after = new { command.Codigo, command.Descripcion, command.AplicaIVA, command.Activo },
            });

        tx.Complete();

        return TipoDeIvaMapper.ToDto(updated);
    }
}
