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

namespace SIGCM2.Application.Products.Update;

public sealed class UpdateProductCommandHandler
    : ICommandHandler<UpdateProductCommand, ProductUpdatedDto>
{
    private readonly IProductRepository _repo;
    private readonly IProductTypeRepository _ptRepo;
    private readonly IRubroRepository _rubroRepo;
    private readonly IAuditLogger _audit;
    private readonly TimeProvider _timeProvider;

    public UpdateProductCommandHandler(
        IProductRepository repo,
        IProductTypeRepository ptRepo,
        IRubroRepository rubroRepo,
        IAuditLogger audit,
        TimeProvider timeProvider)
    {
        _repo = repo;
        _ptRepo = ptRepo;
        _rubroRepo = rubroRepo;
        _audit = audit;
        _timeProvider = timeProvider;
    }

    public async Task<ProductUpdatedDto> Handle(UpdateProductCommand command)
    {
        // 1. Load entity
        var target = await _repo.GetByIdAsync(command.Id)
            ?? throw new ProductNotFoundException(command.Id);

        // 2. Load ProductType (MedioId + ProductTypeId are immutable post-creation)
        var productType = await _ptRepo.GetByIdAsync(target.ProductTypeId)
            ?? throw new ProductTypeNotFoundException(target.ProductTypeId);

        // 3. Flags coherence
        if (productType.RequiresCategory && !command.RubroId.HasValue)
            throw new ProductTipoFlagsIncoherentesException(
                $"El tipo '{productType.Nombre}' requiere RubroId (RequiresCategory=true)", "rubroId");

        if (productType.HasDuration && !command.PriceDurationDays.HasValue)
            throw new ProductTipoFlagsIncoherentesException(
                $"El tipo '{productType.Nombre}' requiere PriceDurationDays (HasDuration=true)", "priceDurationDays");

        // 4. Validate Rubro if provided: must be active
        if (command.RubroId.HasValue)
        {
            var rubro = await _rubroRepo.GetByIdAsync(command.RubroId.Value);
            if (rubro == null || !rubro.Activo)
                throw new RubroInactivoException(command.RubroId.Value);
        }

        // 5. Duplicate nombre check (skip if name unchanged — optimization)
        if (!string.Equals(command.Nombre, target.Nombre, StringComparison.OrdinalIgnoreCase))
        {
            var exists = await _repo.ExistsByNombreAsync(command.Nombre, target.MedioId, target.ProductTypeId, excludeId: command.Id);
            if (exists)
                throw new ProductNombreDuplicadoEnMedioTipoException(target.MedioId, target.ProductTypeId, command.Nombre);
        }

        // 6. Apply mutation (immutable)
        var updated = target.WithUpdated(command.Nombre, command.RubroId, command.BasePrice, command.PriceDurationDays, _timeProvider);

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

        await _repo.UpdateAsync(updated);

        await _audit.LogAsync(
            action: "producto.updated",
            targetType: "Product",
            targetId: command.Id.ToString(),
            metadata: new
            {
                before = new { target.Nombre, target.RubroId, target.BasePrice, target.PriceDurationDays },
                after = new { updated.Nombre, updated.RubroId, updated.BasePrice, updated.PriceDurationDays }
            });

        tx.Complete();

        return new ProductUpdatedDto(
            updated.Id, updated.Nombre,
            updated.MedioId, updated.ProductTypeId, updated.RubroId,
            updated.BasePrice, updated.PriceDurationDays,
            updated.IsActive, updated.FechaCreacion, updated.FechaModificacion);
    }
}
