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

namespace Indotalent.Infrastructure.Database.Demo;

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

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

        var confirmedSalesReturns = await context.SalesReturn
            .Where(sr => sr.Status == SalesReturnStatus.Confirmed)
            .Select(sr => sr.Id)
            .ToListAsync();

        if (!confirmedSalesReturns.Any()) return;

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

            foreach (var creditNoteDate in creditNoteDates)
            {
                if (confirmedSalesReturns.Count == 0) break;

                var status = GetRandomStatus(random);
                var salesReturnId = GetRandomAndRemove(confirmedSalesReturns, random);

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

                var creditNote = new CreditNote
                {
                    AutoNumber = autoNo,
                    CreditNoteDate = creditNoteDate,
                    CreditNoteStatus = status,
                    Description = $"Credit Note for {creditNoteDate:MMMM yyyy}",
                    SalesReturnId = salesReturnId
                };

                await context.CreditNote.AddAsync(creditNote);
            }
        }

        await context.SaveChangesAsync();
    }

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