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

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

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

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

        var now = _timeProvider.GetUtcNow().UtcDateTime;
        var updated = entity.WithDescripcion(command.Descripcion, now);
        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.Descripcion, command.Activo);

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

        tx.Complete();

        return IngresosBrutosMapper.ToDto(updated);
    }
}
