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

namespace Indotalent.Infrastructure.Database.Demo;

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

        var random = new Random();
        var entityName = nameof(SalesOrder);
        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(-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}}/"
                );

                var salesOrder = new SalesOrder
                {
                    AutoNumber = autoNo,
                    OrderDate = transDate,
                    OrderStatus = GetHighProbabilityStatus(random),
                    CustomerId = GetRandomValue(customers, random),
                    TaxId = GetRandomValue(taxes, random),
                };
                await context.SalesOrder.AddAsync(salesOrder);

                int numberOfProducts = random.Next(3, 6);
                for (int i = 0; i < numberOfProducts; i++)
                {
                    var qty = (double)random.Next(2, 5);
                    var product = products[random.Next(products.Count)];
                    var salesOrderItem = new SalesOrderItem
                    {
                        SalesOrderId = salesOrder.Id,
                        ProductId = product.Id,
                        Summary = product.AutoNumber,
                        UnitPrice = product.UnitPrice,
                        Quantity = qty,
                        Total = (product.UnitPrice ?? 0m) * (decimal)qty
                    };
                    await context.SalesOrderItem.AddAsync(salesOrderItem);
                }

                await context.SaveChangesAsync();

                context.RecalculateSalesOrder(salesOrder.Id);
                await context.SaveChangesAsync();
            }
        }
    }

    private static SalesOrderStatus GetHighProbabilityStatus(Random random)
    {
        int probability = random.Next(1, 101);

        if (probability <= 90)
        {
            return SalesOrderStatus.Confirmed;
        }
        else
        {
            var otherStatuses = new[] { SalesOrderStatus.Draft, SalesOrderStatus.Cancelled, SalesOrderStatus.Archived };
            return otherStatuses[random.Next(otherStatuses.Length)];
        }
    }

    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();
    }
}