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.Create;

public sealed class CreateProductTypeCommandHandler
    : ICommandHandler<CreateProductTypeCommand, ProductTypeCreatedDto>
{
    private readonly IProductTypeRepository _repo;
    private readonly IAuditLogger _audit;
    private readonly TimeProvider _timeProvider;

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

    public async Task<ProductTypeCreatedDto> Handle(CreateProductTypeCommand command)
    {
        // 1. Duplicate name check (before factory — avoids wasting domain allocation on error)
        var exists = await _repo.ExistsByNombreAsync(command.Nombre, excludeId: null);
        if (exists)
            throw new ProductTypeNombreDuplicadoException(command.Nombre);

        // 2. Build entity (factory normalizes multimedia if AllowImages=false)
        var entity = ProductType.ForCreation(
            command.Nombre,
            command.HasDuration, command.RequiresText, command.RequiresCategory, command.IsBundle,
            command.AllowImages,
            command.MaxImages, command.MaxImageSizeMB, command.MaxImageWidth, command.MaxImageHeight,
            _timeProvider);

        // 3. Persist + audit (fail-closed: if audit throws, TX rolls back)
        using var tx = new TransactionScope(
            TransactionScopeOption.Required,
            new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted },
            TransactionScopeAsyncFlowOption.Enabled);

        var newId = await _repo.AddAsync(entity);

        await _audit.LogAsync(
            action: "producto_tipo.created",
            targetType: "ProductType",
            targetId: newId.ToString(),
            metadata: new
            {
                after = new
                {
                    entity.Nombre,
                    entity.HasDuration,
                    entity.RequiresText,
                    entity.RequiresCategory,
                    entity.IsBundle,
                    entity.AllowImages,
                    entity.MaxImages,
                    entity.MaxImageSizeMB,
                    entity.MaxImageWidth,
                    entity.MaxImageHeight,
                }
            });

        tx.Complete();

        return new ProductTypeCreatedDto(
            newId, entity.Nombre,
            entity.HasDuration, entity.RequiresText, entity.RequiresCategory, entity.IsBundle,
            entity.AllowImages,
            entity.MaxImages, entity.MaxImageSizeMB, entity.MaxImageWidth, entity.MaxImageHeight,
            entity.IsActive);
    }
}
