using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using CMSMicroservice.Domain.Entities.DiscountShop;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.CreateDiscountCategory;

public class CreateDiscountCategoryCommandHandler : IRequestHandler<CreateDiscountCategoryCommand, long>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<long> Handle(CreateDiscountCategoryCommand request, CancellationToken cancellationToken)
    {
        // بررسی وجود دسته‌بندی با همین نام
        var existingCategory = await _context.DiscountCategories
            .FirstOrDefaultAsync(c => c.Name == request.Name, cancellationToken);

        if (existingCategory != null)
        {
            throw new InvalidOperationException("دسته‌بندی با این نام قبلاً ثبت شده است");
        }

        // بررسی وجود دسته‌بندی والد
        if (request.ParentCategoryId.HasValue)
        {
            var parentExists = await _context.DiscountCategories
                .AnyAsync(c => c.Id == request.ParentCategoryId.Value, cancellationToken);

            if (!parentExists)
            {
                throw new InvalidOperationException("دسته‌بندی والد یافت نشد");
            }
        }

        var category = new DiscountCategory
        {
            Name = request.Name,
            Title = request.Title,
            Description = request.Description,
            ImagePath = request.ImagePath,
            ParentCategoryId = request.ParentCategoryId,
            SortOrder = request.SortOrder,
            IsActive = request.IsActive,
            Created = DateTime.Now
        };

        _context.DiscountCategories.Add(category);
        await _context.SaveChangesAsync(cancellationToken);

        return category.Id;
    }
}
