using System.Transactions;
using SIGCM2.Application.Abstractions;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Audit;
using SIGCM2.Application.Medios.Deactivate;
using SIGCM2.Domain.Entities;
using SIGCM2.Domain.Exceptions;

namespace SIGCM2.Application.Medios.Reactivate;

public sealed class ReactivateMedioCommandHandler : ICommandHandler<ReactivateMedioCommand, MedioStatusDto>
{
    private readonly IMedioRepository _repo;
    private readonly IAuditLogger _audit;
    private readonly TimeProvider _timeProvider;

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

    public async Task<MedioStatusDto> Handle(ReactivateMedioCommand command)
    {
        var target = await _repo.GetByIdAsync(command.Id)
            ?? throw new MedioNotFoundException(command.Id);

        // Idempotent: already active → return as-is without writing an audit event
        if (target.Activo)
            return new MedioStatusDto(target.Id, target.Codigo, target.Activo);

        var now = _timeProvider.GetUtcNow().UtcDateTime;
        var updated = target.WithActivo(true, now);

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

        await _repo.UpdateAsync(updated);

        await _audit.LogAsync(
            action: "medio.reactivate",
            targetType: "Medio",
            targetId: command.Id.ToString());

        tx.Complete();

        return new MedioStatusDto(updated.Id, updated.Codigo, updated.Activo);
    }
}
