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

namespace Indotalent.Infrastructure.Database.Demo;

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

        var random = new Random();
        var entityName = nameof(DebitNote);
        var dateFinish = DateTime.Now;
        var dateStart = new DateTime(dateFinish.AddMonths(-12).Year, dateFinish.AddMonths(-12).Month, 1);

        var confirmedPurchaseReturns = await context.PurchaseReturn
            .Where(pr => pr.Status == PurchaseReturnStatus.Confirmed)
            .Select(pr => pr.Id)
            .ToListAsync();

        if (!confirmedPurchaseReturns.Any()) return;

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

            foreach (var debitNoteDate in debitNoteDates)
            {
                if (confirmedPurchaseReturns.Count == 0) break;

                var status = GetRandomStatus(random);
                var purchaseReturnId = GetRandomAndRemove(confirmedPurchaseReturns, random);

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

                var debitNote = new DebitNote
                {
                    AutoNumber = autoNo,
                    DebitNoteDate = debitNoteDate,
                    DebitNoteStatus = status,
                    Description = $"Debit Note for {debitNoteDate:MMMM yyyy}",
                    PurchaseReturnId = purchaseReturnId
                };

                await context.DebitNote.AddAsync(debitNote);
            }
        }

        await context.SaveChangesAsync();
    }

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

    private static string GetRandomAndRemove(List<string> list, Random random)
    {
        int index = random.Next(list.Count);
        string value = list[index];
        list.RemoveAt(index);
        return value;
    }

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