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

namespace Indotalent.Infrastructure.Database.Demo;

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

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

        var targetCampaigns = await context.Campaign
            .Where(c => c.Status == CampaignStatus.Confirmed ||
                        c.Status == CampaignStatus.OnProgress ||
                        c.Status == CampaignStatus.Finished)
            .Select(c => c.Id)
            .ToListAsync();

        if (!targetCampaigns.Any()) return;

        for (DateTime date = dateStart; date <= dateFinish; date = date.AddMonths(1))
        {
            var transactionDaysList = GetRandomDays(date.Year, date.Month, 8).ToList();

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

                var budget = new Budget
                {
                    AutoNumber = autoNo,
                    Title = $"Budget for {transDate:MMMM yyyy}",
                    Description = $"Description for budget on {transDate:MMMM yyyy}",
                    BudgetDate = transDate,
                    Status = status,
                    Amount = (decimal)(10000 * Math.Ceiling((random.NextDouble() * 89) + 1)),
                    CampaignId = GetRandomValue(targetCampaigns, random)
                };

                await context.Budget.AddAsync(budget);
            }
        }

        await context.SaveChangesAsync();
    }

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