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

namespace Indotalent.Infrastructure.Database.Demo;

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

        var random = new Random();
        var entityName = nameof(SalesQuotation);
        var customers = await context.Customer.Select(x => x.Id).ToListAsync();
        var taxes = await context.Tax.Select(x => x.Id).ToListAsync();
        var products = await context.Product.ToListAsync();

        if (!customers.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[] quotationDates = GetRandomDays(date.Year, date.Month, 4);

            foreach (var quotationDate in quotationDates)
            {
                var status = GetRandomStatus(random);

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

                var salesQuotation = new SalesQuotation
                {
                    AutoNumber = autoNo,
                    QuotationDate = quotationDate,
                    QuotationStatus = status,
                    Description = $"Quotation for {quotationDate:MMMM yyyy}",
                    CustomerId = GetRandomValue(customers, random),
                    TaxId = GetRandomValue(taxes, random),
                };
                await context.SalesQuotation.AddAsync(salesQuotation);

                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 salesQuotationItem = new SalesQuotationItem
                    {
                        SalesQuotationId = salesQuotation.Id,
                        ProductId = product.Id,
                        Summary = product.AutoNumber,
                        UnitPrice = product.UnitPrice,
                        Quantity = qty,
                        Total = (product.UnitPrice ?? 0m) * (decimal)qty
                    };
                    await context.SalesQuotationItem.AddAsync(salesQuotationItem);
                }

                await context.SaveChangesAsync();
                context.RecalculateSalesQuotation(salesQuotation.Id);
                await context.SaveChangesAsync();
            }
        }
    }

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