using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Data.Entities;
using Indotalent.Data.Enums;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Infrastructure.Database.Demo;

public static class SalesReturnSeeder
{
    public static async Task GenerateDataAsync(AppDbContext context)
    {
        if (await context.SalesReturn.AnyAsync()) return;

        var random = new Random();
        var entityName = nameof(SalesReturn);
        var deliveryOrderEntityName = nameof(DeliveryOrder);
        var ivtEntityName = nameof(InventoryTransaction);

        var deliveryOrders = await context.DeliveryOrder
            .Where(x => x.Status >= DeliveryOrderStatus.Confirmed)
            .ToListAsync();

        var warehouses = await context.Warehouse
            .Where(x => x.SystemWarehouse == false)
            .Select(x => x.Id)
            .ToListAsync();

        if (!warehouses.Any()) return;

        foreach (var deliveryOrder in deliveryOrders)
        {
            bool skip = random.Next(2) == 0;

            if (skip) continue;

            var autoNo = await context.GenerateAutoNumberAsync(
                entityName: entityName,
                prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/"
            );

            var salesReturn = new SalesReturn
            {
                AutoNumber = autoNo,
                ReturnDate = deliveryOrder.DeliveryDate?.AddDays(random.Next(1, 5)),
                Status = GetRandomStatus(random),
                DeliveryOrderId = deliveryOrder.Id,
            };
            await context.SalesReturn.AddAsync(salesReturn);

            var items = await context.InventoryTransaction
                .Where(x => x.ModuleId == deliveryOrder.Id && x.ModuleName == deliveryOrderEntityName)
                .ToListAsync();

            foreach (var item in items)
            {
                var autoNoIVT = await context.GenerateAutoNumberAsync(
                    entityName: ivtEntityName,
                    prefixTemplate: $"{ivtEntityName.ToShortNameConsonant(3)}/{{Year}}/"
                );

                var inventoryTransaction = new InventoryTransaction
                {
                    ModuleId = salesReturn.Id,
                    ModuleName = entityName,
                    ModuleCode = "SRN",
                    ModuleNumber = salesReturn.AutoNumber,
                    MovementDate = salesReturn.ReturnDate!.Value,
                    Status = (InventoryTransactionStatus)salesReturn.Status,
                    AutoNumber = autoNoIVT,
                    WarehouseId = GetRandomValue(warehouses, random),
                    ProductId = item.ProductId,
                    Movement = item.Movement
                };

                context.CalculateInvenTrans(inventoryTransaction);
                await context.InventoryTransaction.AddAsync(inventoryTransaction);
            }

            await context.SaveChangesAsync();
        }
    }

    private static SalesReturnStatus GetRandomStatus(Random random)
    {
        var statuses = new[] { SalesReturnStatus.Draft, SalesReturnStatus.Cancelled, SalesReturnStatus.Confirmed, SalesReturnStatus.Archived };
        var weights = new[] { 1, 1, 4, 1 };

        int totalWeight = weights.Sum();
        int randomNumber = random.Next(0, totalWeight);

        for (int i = 0; i < statuses.Length; i++)
        {
            if (randomNumber < weights[i]) return statuses[i];
            randomNumber -= weights[i];
        }

        return SalesReturnStatus.Confirmed;
    }

    private static T GetRandomValue<T>(List<T> list, Random random)
    {
        return list[random.Next(list.Count)];
    }
}