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.ProductTypes.Update;

public sealed class UpdateProductTypeCommandHandler
    : ICommandHandler<UpdateProductTypeCommand, ProductTypeUpdatedDto>
{
    private readonly IProductTypeRepository _repo;
    private readonly IAuditLogger _audit;
    private readonly TimeProvider _timeProvider;

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

    public async Task<ProductTypeUpdatedDto> Handle(UpdateProductTypeCommand command)
    {
        // 1. Load entity (throws if not found)
        var target = await _repo.GetByIdAsync(command.Id)
            ?? throw new ProductTypeNotFoundException(command.Id);

        // 2. If nombre changed, check for duplicate (skip call when same name — optimization)
        if (!string.Equals(command.Nombre, target.Nombre, StringComparison.OrdinalIgnoreCase))
        {
            var duplicateExists = await _repo.ExistsByNombreAsync(command.Nombre, excludeId: command.Id);
            if (duplicateExists)
                throw new ProductTypeNombreDuplicadoException(command.Nombre);
        }

        // 3. Build updated entity via With* methods (immutable, each returns new instance)
        var updated = target
            .WithRenamed(command.Nombre, _timeProvider)
            .WithUpdatedFlags(command.HasDuration, command.RequiresText, command.RequiresCategory, command.IsBundle, _timeProvider)
            .WithUpdatedMultimedia(command.AllowImages, command.MaxImages, command.MaxImageSizeMB, command.MaxImageWidth, command.MaxImageHeight, _timeProvider);

        // 4. Persist + audit (fail-closed)
        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_tipo.updated",
            targetType: "ProductType",
            targetId: command.Id.ToString(),
            metadata: new
            {
                before = new { target.Nombre, target.HasDuration, target.RequiresText, target.RequiresCategory, target.IsBundle, target.AllowImages },
                after = new { updated.Nombre, updated.HasDuration, updated.RequiresText, updated.RequiresCategory, updated.IsBundle, updated.AllowImages }
            });

        tx.Complete();

        return new ProductTypeUpdatedDto(
            updated.Id, updated.Nombre,
            updated.HasDuration, updated.RequiresText, updated.RequiresCategory, updated.IsBundle,
            updated.AllowImages,
            updated.MaxImages, updated.MaxImageSizeMB, updated.MaxImageWidth, updated.MaxImageHeight,
            updated.IsActive, updated.FechaModificacion);
    }
}
