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

namespace Indotalent.Infrastructure.Database.Demo;

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

        var random = new Random();
        var entityName = nameof(PurchaseRequisition);
        var vendors = await context.Vendor.Select(x => x.Id).ToListAsync();
        var taxes = await context.Tax.Select(x => x.Id).ToListAsync();
        var products = await context.Product.ToListAsync();

        if (!vendors.Any() || !taxes.Any() || !products.Any()) return;

        var dateFinish = DateTime.Now;
        var dateStart = new DateTime(dateFinish.AddMonths(-11).Year, dateFinish.AddMonths(-11).Month, 1);

        for (DateTime date = dateStart; date <= dateFinish; date = date.AddMonths(1))
        {
            DateTime[] requisitionDates = GetRandomDays(date.Year, date.Month, 4);

            foreach (var requisitionDate in requisitionDates)
            {
                var status = GetRandomStatus(random);

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

                var purchaseRequisition = new PurchaseRequisition
                {
                    AutoNumber = autoNo,
                    RequisitionDate = requisitionDate,
                    RequisitionStatus = status,
                    Description = $"Requisition for {requisitionDate:MMMM yyyy}",
                    VendorId = GetRandomValue(vendors, random),
                    TaxId = GetRandomValue(taxes, random),
                };
                await context.PurchaseRequisition.AddAsync(purchaseRequisition);

                int numberOfItems = random.Next(2, 5);
                for (int i = 0; i < numberOfItems; i++)
                {
                    var qty = (double)random.Next(2, 5);
                    var product = products[random.Next(products.Count)];

                    var purchaseRequisitionItem = new PurchaseRequisitionItem
                    {
                        PurchaseRequisitionId = purchaseRequisition.Id,
                        ProductId = product.Id,
                        Summary = product.AutoNumber,
                        UnitPrice = product.UnitPrice,
                        Quantity = qty,
                        Total = (product.UnitPrice ?? 0m) * (decimal)qty
                    };
                    await context.PurchaseRequisitionItem.AddAsync(purchaseRequisitionItem);
                }

                await context.SaveChangesAsync();
                context.RecalculatePurchaseRequisition(purchaseRequisition.Id);
                await context.SaveChangesAsync();
            }
        }
    }

    private static PurchaseRequisitionStatus GetRandomStatus(Random random)
    {
        var statuses = new[] {
            PurchaseRequisitionStatus.Draft,
            PurchaseRequisitionStatus.Cancelled,
            PurchaseRequisitionStatus.Confirmed,
            PurchaseRequisitionStatus.Ordered
        };
        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 PurchaseRequisitionStatus.Confirmed;
    }

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

    private static DateTime[] GetRandomDays(int year, int month, int count)
    {
        var random = new Random();
        int daysInMonthCount = DateTime.DaysInMonth(year, month);
        var daysInMonth = Enumerable.Range(1, daysInMonthCount).ToList();
        var selectedDays = new List<int>();

        for (int i = 0; i < count && daysInMonth.Count > 0; i++)
        {
            int day = daysInMonth[random.Next(daysInMonth.Count)];
            selectedDays.Add(day);
            daysInMonth.Remove(day);
        }

        return selectedDays.Select(day => new DateTime(year, month, day)).ToArray();
    }
}