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

namespace Indotalent.Infrastructure.Database.Demo;

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

        var random = new Random();
        var entityName = nameof(Expense);
        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))
        {
            DateTime[] expenseDates = GetRandomDays(date.Year, date.Month, 5);

            foreach (var expenseDate in expenseDates)
            {
                var status = GetRandomStatus(random);

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

                var expense = new Expense
                {
                    AutoNumber = autoNo,
                    Title = $"Expense for {expenseDate:MMMM yyyy}",
                    Description = $"Description for expense on {expenseDate:MMMM yyyy}",
                    ExpenseDate = expenseDate,
                    Status = status,
                    Amount = (decimal)(1000 * Math.Ceiling((random.NextDouble() * 89) + 1)),
                    CampaignId = GetRandomValue(targetCampaigns, random)
                };

                await context.Expense.AddAsync(expense);
            }
        }

        await context.SaveChangesAsync();
    }

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