using CMSMicroservice.Application.Common.FileManager;
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;
    private readonly IFileManager _fileManager;

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

    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 ?? string.Empty,
            ThumbnailPath = request.ThumbnailPath ?? string.Empty,
            RemainingCount = 0,
            Rate = 0,
            SaleCount = 0,
            ViewCount = 0,
            IsActive = request.IsActive
        };

        // آپلود تصویر اصلی (اگر فایل ارسال شده باشد)
        if (request.ImageFileBytes is { Length: > 0 })
        {
            var result = await _fileManager.UploadImageAsync(
                "Images/DiscountProducts",
                request.ImageFileBytes,
                request.ImageFileMime ?? "image/jpeg",
                request.ImageFileName,
                cancellationToken);

            product.ImagePath = result.Main.Path;
            product.ThumbnailPath = result.Thumbnail.Path;
        }

        // آپلود بندانگشتی جداگانه (اختیاری)
        if (request.ThumbnailFileBytes is { Length: > 0 })
        {
            var thumbResult = await _fileManager.UploadAsync(
                "Images/DiscountProducts/Thumbnails",
                request.ThumbnailFileBytes,
                request.ThumbnailFileMime ?? "image/jpeg",
                request.ThumbnailFileName,
                cancellationToken);

            product.ThumbnailPath = thumbResult.Path;
        }

        _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;
    }
}
