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

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.CreateDiscountProduct;

public class CreateDiscountProductCommandHandler : IRequestHandler<CreateDiscountProductCommand, long>
{
    private readonly IApplicationDbContext _context;
    private readonly IInventoryService _inventoryService;

    public CreateDiscountProductCommandHandler(
        IApplicationDbContext context,
        IInventoryService inventoryService)
    {
        _context = context;
        _inventoryService = inventoryService;
    }

    public async Task<long> Handle(CreateDiscountProductCommand request, CancellationToken cancellationToken)
    {
        var product = new DiscountProduct
        {
            Title = request.Title,
            ShortInfomation = request.ShortInfomation,
            FullInformation = request.FullInformation,
            Price = request.Price,
            MaxDiscountPercent = request.MaxDiscountPercent,
            ImagePath = request.ImagePath,
            ThumbnailPath = request.ThumbnailPath,
            RemainingCount = 0, // موجودی اولیه صفر - باید از طریق Inventory اضافه شود
            Rate = 0,
            SaleCount = 0,
            ViewCount = 0,
            IsActive = true
        };

        _context.DiscountProducts.Add(product);
        await _context.SaveChangesAsync(cancellationToken);

        // ایجاد رکورد موجودی در سیستم انبارداری با موجودی اولیه صفر
        await _inventoryService.InitializeInventoryAsync(
            product.Id,
            ProductType.DiscountProduct,
            0, // موجودی اولیه صفر - باید از طریق Inventory اضافه شود
            ct: cancellationToken);

        // Add product categories
        if (request.CategoryIds.Any())
        {
            var productCategories = request.CategoryIds.Select(categoryId => new DiscountProductCategory
            {
                ProductId = product.Id,
                CategoryId = categoryId
            }).ToList();

            _context.DiscountProductCategories.AddRange(productCategories);
            await _context.SaveChangesAsync(cancellationToken);
        }

        return product.Id;
    }
}
