using System.Transactions;
using SIGCM2.Application.Abstractions;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Audit;
using SIGCM2.Application.Common;

namespace SIGCM2.Application.Pricing.ChargeableChars.Reactivate;

/// <summary>
/// PRC-001 — Handler for ReactivateChargeableCharConfigCommand.
/// Flow: open TransactionScope → ReactivateAsync (SP with guard) → audit → tx.Complete().
///
/// Guard failures (ALREADY_ACTIVE / VIGENTE_EXISTS / POSTERIOR_ROWS_EXIST) are thrown by the
/// repository as ChargeableCharConfigReactivationNotAllowedException and propagate to the
/// ExceptionFilter which maps them to HTTP 409.
/// </summary>
public sealed class ReactivateChargeableCharConfigCommandHandler
    : ICommandHandler<ReactivateChargeableCharConfigCommand, ReactivateChargeableCharConfigResponse>
{
    private readonly IChargeableCharConfigRepository _repo;
    private readonly IAuditLogger _audit;
    private readonly TimeProvider _timeProvider;

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

    public async Task<ReactivateChargeableCharConfigResponse> Handle(
        ReactivateChargeableCharConfigCommand command)
    {
        // Open TX before calling SP so that audit failure rolls back the SP work.
        using var tx = new TransactionScope(
            TransactionScopeOption.Required,
            new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted },
            TransactionScopeAsyncFlowOption.Enabled);

        // SP enforces guard rules; throws ChargeableCharConfigReactivationNotAllowedException on failure.
        // Returns the reactivated entity so we can populate the response and the audit log.
        var reactivated = await _repo.ReactivateAsync(command.Id, CancellationToken.None);

        await _audit.LogAsync(
            action: "tasacion.chargeable_char.reactivate",
            targetType: "ChargeableCharConfig",
            targetId: command.Id.ToString(),
            metadata: new
            {
                id = reactivated.Id,
                symbol = reactivated.Symbol,
                productTypeId = reactivated.ProductTypeId,
                validFrom = reactivated.ValidFrom.ToString("yyyy-MM-dd"),
                reactivatedOn = _timeProvider.GetArgentinaToday().ToString("yyyy-MM-dd"),
            });

        tx.Complete();

        return new ReactivateChargeableCharConfigResponse(
            Id: reactivated.Id,
            ProductTypeId: reactivated.ProductTypeId,
            Symbol: reactivated.Symbol,
            Category: reactivated.Category,
            PricePerUnit: reactivated.PricePerUnit,
            ValidFrom: reactivated.ValidFrom,
            IsActive: reactivated.IsActive);
    }
}
