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

namespace SIGCM2.Application.IngresosBrutos.Create;

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

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

    public async Task<IngresosBrutosDto> Handle(CreateIngresosBrutosCommand command)
    {
        var entity = Domain.Entities.IngresosBrutos.ForCreation(
            command.Provincia,
            command.Descripcion,
            command.Alicuota,
            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);

        await _audit.LogAsync(
            action: "ingresos_brutos.create",
            targetType: "IngresosBrutos",
            targetId: newId.ToString(),
            metadata: new { entity.Provincia, entity.Alicuota, entity.VigenciaDesde });

        tx.Complete();

        return IngresosBrutosMapper.ToDto(Domain.Entities.IngresosBrutos.FromDb(
            id: newId,
            provincia: entity.Provincia,
            descripcion: entity.Descripcion,
            alicuota: entity.Alicuota,
            activo: entity.Activo,
            vigenciaDesde: entity.VigenciaDesde,
            vigenciaHasta: entity.VigenciaHasta,
            predecesorId: entity.PredecesorId,
            fechaCreacion: _timeProvider.GetUtcNow().UtcDateTime,
            fechaModificacion: null));
    }
}
