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

public sealed class CreateProductCommandHandler
    : ICommandHandler<CreateProductCommand, ProductCreatedDto>
{
    private readonly IProductRepository _repo;
    private readonly IProductTypeRepository _ptRepo;
    private readonly IMedioRepository _medioRepo;
    private readonly IRubroRepository _rubroRepo;
    private readonly IAuditLogger _audit;
    private readonly TimeProvider _timeProvider;

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

    public async Task<ProductCreatedDto> Handle(CreateProductCommand command)
    {
        // 1. Validate Medio exists and is active
        var medio = await _medioRepo.GetByIdAsync(command.MedioId)
            ?? throw new MedioNotFoundException(command.MedioId);
        if (!medio.Activo)
            throw new MedioInactivoException(command.MedioId);

        // 2. Validate ProductType exists and is active
        var productType = await _ptRepo.GetByIdAsync(command.ProductTypeId)
            ?? throw new ProductTypeNotFoundException(command.ProductTypeId);
        if (!productType.IsActive)
            throw new ProductTypeInactivoException(command.ProductTypeId);

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

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

        // 5. 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);
        }

        // 6. Duplicate nombre check (filtered on IsActive=1 — allows reuse after soft-delete)
        var exists = await _repo.ExistsByNombreAsync(command.Nombre, command.MedioId, command.ProductTypeId, excludeId: null);
        if (exists)
            throw new ProductNombreDuplicadoEnMedioTipoException(command.MedioId, command.ProductTypeId, command.Nombre);

        // 7. Build entity
        var entity = Product.ForCreation(
            command.Nombre, command.MedioId, command.ProductTypeId,
            command.RubroId, command.BasePrice, command.PriceDurationDays,
            _timeProvider);

        // 8. Persist + audit (fail-closed)
        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.created",
            targetType: "Product",
            targetId: newId.ToString(),
            metadata: new
            {
                after = new
                {
                    entity.Nombre,
                    entity.MedioId,
                    entity.ProductTypeId,
                    entity.RubroId,
                    entity.BasePrice,
                    entity.PriceDurationDays,
                }
            });

        tx.Complete();

        return new ProductCreatedDto(
            newId, entity.Nombre,
            entity.MedioId, entity.ProductTypeId, entity.RubroId,
            entity.BasePrice, entity.PriceDurationDays,
            entity.IsActive, entity.FechaCreacion);
    }
}
