using AyCode.Core.Loggers;
using AyCode.Services.SignalRs;
using FruitBank.Common.Dtos;
using FruitBank.Common.Entities;
using FruitBank.Common.Enums;
using FruitBank.Common.Server.Interfaces;
using FruitBank.Common.Server.Services.SignalRs;
using FruitBank.Common.SignalRs;
using Mango.Nop.Core.Loggers;
using Nop.Core;
using Nop.Core.Domain.Orders;
using Nop.Core.Events;
using Nop.Plugin.Misc.FruitBankPlugin.Domains.DataLayer;

namespace Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers;

public class StockSignalREndpointServer(StockTakingDbContext ctx, SignalRSendToClientService sendToClient, IEventPublisher eventPublisher, IWorkContext workContext, IEnumerable<IAcLogWriterBase> logWriters)
    : IStockSignalREndpointServer
{
    private const int LastStockTakingDays = 15;
    private readonly ILogger _logger = new Logger<StockSignalREndpointServer>(logWriters.ToArray());

    private static StockTakingItem CreateStockTakingItem(int stockTakingId, ProductDto productDto, IEnumerable<OrderItemDto> orderItemDtos)
    {
        //if (productDto.StockQuantity < 0 && productDto.IncomingQuantity > 0)
        //{
        //    _logger.Info($"Beszállítás alatt lévő 'virtuális' készlet, nem leltározzuk! product: [#{productDto.Id}] {productDto.Name}; StockQuantity: {productDto.StockQuantity}; IncomingQuantity: {productDto.IncomingQuantity}");
        //    return null;
        //}

        var stockTakingItem = new StockTakingItem { StockTakingId = stockTakingId };
        UpdateStockTakingItemValues(stockTakingItem, productDto, orderItemDtos);

        return stockTakingItem;
    }

    private static void UpdateStockTakingItemValues(StockTakingItem stockTakingItem, ProductDto productDto, IEnumerable<OrderItemDto> orderItemDtos)
    {
        stockTakingItem.ProductId = productDto.Id;
        stockTakingItem.IsMeasurable = productDto.IsMeasurable;
        stockTakingItem.OriginalStockQuantity = productDto.StockQuantity;
        stockTakingItem.InProcessOrdersQuantity = orderItemDtos.Sum(x => x.Quantity);
        //A NetWeight-et nem növeljük meg, mert az nem vonódik le automatikusan a rendelés létrehozásakor! - J.
        stockTakingItem.OriginalNetWeight = productDto.NetWeight; //double.Round(productDto.NetWeight + orderItemDtos[productDto.Id].Sum(x => x.NetWeight), 1)
    }

    [SignalR(SignalRTags.GetStockTakings)]
    public async Task<List<StockTaking>> GetStockTakings(bool loadRelations)
    {
        _logger.Debug($"GetStockTakings invoke. loadRelations: {loadRelations}");
        return await ctx.StockTakings.GetAll(loadRelations).ToListAsync();
    }

    public async Task<List<StockTaking>> GetStockTakingsByProductId(int productId)
    {
        throw new NotImplementedException();
    }

    [SignalR(SignalRTags.CloseStockTaking)]
    public async Task<StockTaking> CloseStockTaking(int stockTakingId)
    {
        var result = await ctx.TransactionSafeAsync(async _ =>
        {
            await ctx.CloseStockTaking(stockTakingId);
            return true;
        });

        if (result) return await ctx.StockTakings.GetByIdAsync(stockTakingId, false);

        _logger.Error($"StockTaking closing ERROR! stockTakingId: {stockTakingId}");
        return null;
    }

    [SignalR(SignalRTags.AddStockTaking)]
    public async Task<StockTaking> AddStockTaking(StockTaking stockTaking)
    {
        var result = await ctx.TransactionSafeAsync(async _ =>
        {
            stockTaking.IsClosed = false;
            stockTaking.StartDateTime = DateTime.Now;

            await ctx.StockTakings.InsertAsync(stockTaking);

            var productDtos = await ctx.ProductDtos.GetAll(true).ToListAsync();

            var orderItemDtos = (await ctx.OrderItemDtos.GetAllByProductIds(productDtos.Select(p => p.Id), true)
                    .Where(oi => oi.OrderDto.OrderStatusId != (int)OrderStatus.Complete).ToArrayAsync())
                .Where(oi => oi.MeasuringStatus == MeasuringStatus.NotStarted).ToLookup(k => k.ProductId, v => v);
            
            foreach (var productDto in productDtos)
            {
                var stockTakingItem = CreateStockTakingItem(stockTaking.Id, productDto, orderItemDtos[productDto.Id]);
                if (stockTakingItem == null) continue;

                await ctx.StockTakingItems.InsertAsync(stockTakingItem);
            }

            return true;
        });

        if (result) return await ctx.StockTakings.GetByIdAsync(stockTaking.Id, false);
        return null;
    }

    [SignalR(SignalRTags.RefreshStockTakingItem)]
    public async Task<StockTakingItem> RefreshStockTakingItem(int stockTakingItemId)
    {
        var result = await ctx.TransactionSafeAsync(async _ =>
        {
            var stockTakingItem = await ctx.StockTakingItems.GetByIdAsync(stockTakingItemId, true);

            if (stockTakingItem?.StockTaking == null || stockTakingItem.StockTaking.IsClosed || stockTakingItem.IsMeasured)
            {
                _logger.Error($"StockTakingItem refresh ERROR! stockTakingItemId: {stockTakingItemId}; StockTaking is closed: {stockTakingItem?.StockTaking?.IsClosed}; IsMeasured: {stockTakingItem?.IsMeasured}");
                return false;
            }

            var productDto = await ctx.ProductDtos.GetByIdAsync(stockTakingItem.ProductId, true);

            var orderItemDtos = (await ctx.OrderItemDtos.GetAllByProductId(productDto.Id, true)
                .Where(oi => oi.OrderDto.OrderStatusId != (int)OrderStatus.Complete).ToArrayAsync())
                .Where(oi => oi.MeasuringStatus == MeasuringStatus.NotStarted);

            UpdateStockTakingItemValues(stockTakingItem, productDto, orderItemDtos);

            await ctx.StockTakingItems.UpdateAsync(stockTakingItem);
            return true;
        });

        if (result) return await ctx.StockTakingItems.GetByIdAsync(stockTakingItemId, false);
        return null;
    }

    [SignalR(SignalRTags.UpdateStockTaking)]
    public async Task<StockTaking> UpdateStockTaking(StockTaking stockTaking)
    {
        if(stockTaking == null) return null;

        await ctx.StockTakings.UpdateAsync(stockTaking);
        return await ctx.StockTakings.GetByIdAsync(stockTaking.Id, true);
    }

    [SignalR(SignalRTags.GetStockTakingItems)]
    public async Task<List<StockTakingItem>> GetStockTakingItems()
    {
        return await ctx.StockTakingItems.GetAll(true).ToListAsync();
    }

    [SignalR(SignalRTags.GetStockTakingItemsById)]
    public async Task<StockTakingItem> GetStockTakingItemsById(int stockTakingItemId)
    {
        var result = await ctx.StockTakingItems.GetByIdAsync(stockTakingItemId, true);
        return result;
    }

    [SignalR(SignalRTags.GetStockTakingItemsByProductId)]
    public async Task<List<StockTakingItem>> GetStockTakingItemsByProductId(int productId)
    {
        return await ctx.StockTakingItems.GetAllByProductId(productId, true).ToListAsync();
    }

    [SignalR(SignalRTags.GetStockTakingItemsByStockTakingId)]
    public async Task<List<StockTakingItem>> GetStockTakingItemsByStockTakingId(int stockTakingId)
    {
        return await ctx.StockTakingItems.GetAllByStockTakingId(stockTakingId, true).ToListAsync();
    }

    public async Task<StockTakingItem> AddStockTakingItem(StockTakingItem stockTakingItem)
    {
        throw new NotImplementedException();
    }

    public async Task<StockTakingItem> UpdateStockTakingItem(StockTakingItem stockTakingItem)
    {
        throw new NotImplementedException();
    }

    public async Task<List<StockTakingItemPallet>> GetStockTakingItemPallets()
    {
        throw new NotImplementedException();
    }

    public async Task<List<StockTakingItemPallet>> GetStockTakingItemPalletsByProductId(int productId)
    {
        throw new NotImplementedException();
    }

    public async Task<StockTakingItemPallet> AddStockTakingItemPallet(StockTakingItemPallet stockTakingItemPallet)
    {
        return await ctx.AddStockTakingItemPallet(stockTakingItemPallet);
    }

    public async Task<StockTakingItemPallet> UpdateStockTakingItemPallet(StockTakingItemPallet stockTakingItemPallet)
    {
        return await ctx.UpdateStockTakingItemPallet(stockTakingItemPallet);
    }

    [SignalR(SignalRTags.AddOrUpdateMeasuredStockTakingItemPallet)]
    public async Task<StockTakingItemPallet> AddOrUpdateMeasuredStockTakingItemPallet(StockTakingItemPallet stockTakingItemPallet)
    {
        stockTakingItemPallet.IsMeasured = true;
        return await ctx.AddOrUpdateMeasuredStockTakingItemPallet(stockTakingItemPallet);
    }
}