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

namespace Indotalent.Infrastructure.Database.Demo;

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

        var random = new Random();
        var entityName = nameof(PurchaseOrder);
        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 allStatusValues = Enum.GetValues(typeof(PurchaseOrderStatus))
            .Cast<PurchaseOrderStatus>()
            .ToList();

        var nonConfirmedStatusValues = allStatusValues
            .Where(x => x != PurchaseOrderStatus.Confirmed)
            .ToList();

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

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

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

                PurchaseOrderStatus selectedStatus;
                int probability = random.Next(1, 101);

                if (probability <= 90)
                {
                    selectedStatus = PurchaseOrderStatus.Confirmed;
                }
                else
                {
                    selectedStatus = nonConfirmedStatusValues[random.Next(nonConfirmedStatusValues.Count)];
                }

                var purchaseOrder = new PurchaseOrder
                {
                    AutoNumber = autoNo,
                    OrderDate = transDate,
                    OrderStatus = selectedStatus,
                    VendorId = GetRandomValue(vendors, random),
                    TaxId = GetRandomValue(taxes, random),
                };
                await context.PurchaseOrder.AddAsync(purchaseOrder);

                int numberOfProducts = random.Next(3, 6);
                for (int i = 0; i < numberOfProducts; i++)
                {
                    var product = products[random.Next(products.Count)];
                    var quantity = random.Next(20, 50);
                    var purchaseOrderItem = new PurchaseOrderItem
                    {
                        PurchaseOrderId = purchaseOrder.Id,
                        ProductId = product.Id,
                        Summary = product.AutoNumber,
                        UnitPrice = product.UnitPrice,
                        Quantity = (double)quantity,
                        Total = product.UnitPrice * (decimal)quantity
                    };
                    await context.PurchaseOrderItem.AddAsync(purchaseOrderItem);
                }

                await context.SaveChangesAsync();

                context.RecalculatePurchaseOrder(purchaseOrder.Id);
                await context.SaveChangesAsync();
            }
        }
    }

    private static T GetRandomValue<T>(List<T> 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();
    }
}