using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.TagCQ.Commands.AssignTagToProduct;

public class AssignTagToProductCommandHandler : IRequestHandler<AssignTagToProductCommand, Unit>
{
    private readonly IApplicationDbContext _context;

    public AssignTagToProductCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<Unit> Handle(AssignTagToProductCommand request, CancellationToken cancellationToken)
    {
        // بررسی وجود محصول
        var product = await _context.Products
            .FirstOrDefaultAsync(p => p.Id == request.ProductId, cancellationToken);

        if (product == null)
        {
            throw new NotFoundException(nameof(Product), request.ProductId);
        }

        // بررسی وجود تگ
        var tag = await _context.Tags
            .FirstOrDefaultAsync(t => t.Id == request.TagId, cancellationToken);

        if (tag == null)
        {
            throw new NotFoundException(nameof(Tag), request.TagId);
        }

        // بررسی اینکه قبلاً اختصاص داده نشده باشد
        var existingProductTag = await _context.ProductTags
            .FirstOrDefaultAsync(pt => pt.ProductId == request.ProductId && pt.TagId == request.TagId, cancellationToken);

        if (existingProductTag != null)
        {
            throw new BadRequestException("این تگ قبلاً به این محصول اختصاص داده شده است");
        }

        var productTag = new ProductTag
        {
            ProductId = request.ProductId,
            TagId = request.TagId
        };

        _context.ProductTags.Add(productTag);
        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
