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

namespace Indotalent.Infrastructure.Database.Demo;

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

        var random = new Random();
        var entityName = nameof(ProgramManager);
        var programManagerResources = await context.ProgramManagerResource.Select(x => x.Id).ToListAsync();

        if (!programManagerResources.Any()) return;

        var statusValues = Enum.GetValues(typeof(ProgramManagerStatus)).Cast<ProgramManagerStatus>().ToList();
        var priorityValues = Enum.GetValues(typeof(ProgramManagerPriority)).Cast<ProgramManagerPriority>().ToList();

        var dateFinish = DateTime.Now;
        var dateStart = new DateTime(dateFinish.AddMonths(-6).Year, dateFinish.AddMonths(-6).Month, 1);

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

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

                var programManager = new ProgramManager
                {
                    Title = autoNo,
                    AutoNumber = autoNo,
                    Summary = $"Lorem Ipsum Dolor Sit Amet Program - #{Guid.NewGuid().ToString().Substring(0, 5)}",
                    ProgramManagerResourceId = GetRandomValue(programManagerResources, random),
                    Status = statusValues[random.Next(statusValues.Count)],
                    Priority = priorityValues[random.Next(priorityValues.Count)]
                };

                await context.ProgramManager.AddAsync(programManager);
            }
        }

        await context.SaveChangesAsync();
    }

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