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

namespace SIGCM2.Application.TiposDeIva.Create;

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

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

    public async Task<TipoDeIvaDto> Handle(CreateTipoDeIvaCommand command)
    {
        var entity = TipoDeIva.ForCreation(
            command.Codigo,
            command.Descripcion,
            command.Porcentaje,
            command.AplicaIVA,
            command.VigenciaDesde,
            command.VigenciaHasta);

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

        var newId = await _repo.InsertAsync(entity);

        // fail-closed: if LogAsync throws, tx rolls back
        await _audit.LogAsync(
            action: "tipo_iva.create",
            targetType: "TipoDeIva",
            targetId: newId.ToString(),
            metadata: new { entity.Codigo, entity.Porcentaje, entity.VigenciaDesde });

        tx.Complete();

        return TipoDeIvaMapper.ToDto(TipoDeIva.FromDb(
            id: newId,
            codigo: entity.Codigo,
            descripcion: entity.Descripcion,
            porcentaje: entity.Porcentaje,
            aplicaIVA: entity.AplicaIVA,
            activo: entity.Activo,
            vigenciaDesde: entity.VigenciaDesde,
            vigenciaHasta: entity.VigenciaHasta,
            predecesorId: entity.PredecesorId,
            fechaCreacion: _timeProvider.GetUtcNow().UtcDateTime,
            fechaModificacion: null));
    }
}
