using System.Transactions;
using SIGCM2.Application.Abstractions;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Audit;
using SIGCM2.Application.Common;
using SIGCM2.Application.Usuarios.GetById;
using SIGCM2.Domain.Exceptions;

namespace SIGCM2.Application.Usuarios.Reactivate;

public sealed class ReactivateUsuarioCommandHandler : ICommandHandler<ReactivateUsuarioCommand, UsuarioDetailDto>
{
    private readonly IUsuarioRepository _repository;
    private readonly IAuditLogger _audit;
    private readonly TimeProvider _timeProvider;

    public ReactivateUsuarioCommandHandler(
        IUsuarioRepository repository,
        IAuditLogger audit,
        TimeProvider timeProvider)
    {
        _repository = repository;
        _audit = audit;
        _timeProvider = timeProvider;
    }

    public async Task<UsuarioDetailDto> Handle(ReactivateUsuarioCommand cmd)
    {
        var target = await _repository.GetByIdAsync(cmd.UsuarioId)
            ?? throw new UsuarioNotFoundException(cmd.UsuarioId);

        // Idempotent: already active → return as-is without touching FechaModificacion
        if (target.Activo)
        {
            return new UsuarioDetailDto(
                target.Id, target.Username, target.Nombre, target.Apellido,
                target.Email, target.Rol, target.Activo, target.MustChangePassword,
                target.UltimoLogin, target.FechaModificacion);
        }

        var fields = new UpdateUsuarioFields(target.Nombre, target.Apellido, target.Email, target.Rol, true);
        var now = _timeProvider.GetUtcNow().UtcDateTime;

        using (var tx = new TransactionScope(
            TransactionScopeOption.Required,
            new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted },
            TransactionScopeAsyncFlowOption.Enabled))
        {
            await _repository.UpdateAsync(cmd.UsuarioId, fields, now);

            await _audit.LogAsync(
                action: "usuario.reactivate",
                targetType: "Usuario",
                targetId: cmd.UsuarioId.ToString());

            tx.Complete();
        }

        var updated = await _repository.GetDetailAsync(cmd.UsuarioId)
            ?? throw new UsuarioNotFoundException(cmd.UsuarioId);

        return new UsuarioDetailDto(
            updated.Id, updated.Username, updated.Nombre, updated.Apellido,
            updated.Email, updated.Rol, updated.Activo, updated.MustChangePassword,
            updated.UltimoLogin, updated.FechaModificacion);
    }
}
