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

namespace Indotalent.Infrastructure.Database.Demo;

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

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

        var leads = await context.Lead.Select(l => l.Id).ToListAsync();

        if (!leads.Any()) return;

        var activityTypeValues = Enum.GetValues(typeof(LeadActivityType)).Cast<LeadActivityType>().ToList();

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

            foreach (var activityDate in activityDates)
            {
                var leadId = GetRandomValue(leads, random);
                var fromDate = activityDate;
                var toDate = fromDate.AddHours(random.Next(1, 5));

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

                var leadActivity = new LeadActivity
                {
                    LeadId = leadId,
                    AutoNumber = autoNo,
                    Summary = $"Activity on {fromDate:MMMM d, yyyy}",
                    Description = $"Description for activity on {fromDate:MMMM d, yyyy}",
                    FromDate = fromDate,
                    ToDate = toDate,
                    Type = activityTypeValues[random.Next(activityTypeValues.Count)],
                    AttachmentName = random.Next(1, 100) % 2 == 0 ? $"file_{random.Next(1, 100)}.pdf" : null
                };

                await context.LeadActivity.AddAsync(leadActivity);
            }
        }

        await context.SaveChangesAsync();
    }

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