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

namespace Indotalent.Infrastructure.Database.Demo;

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

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

        var salesTeamIds = await context.SalesTeam
            .Select(st => st.Id)
            .ToListAsync();

        if (!salesTeamIds.Any()) return;

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

            foreach (var campaignStart in campaignStarts)
            {
                var duration = random.Next(1, 4);
                var campaignEnd = campaignStart.AddMonths(duration);

                var status = GetRandomStatus(random);

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

                string firstFourChars = autoNo.Length >= 4 ? autoNo.Substring(0, 4) : autoNo;

                var campaign = new Campaign
                {
                    AutoNumber = autoNo,
                    Title = $"{firstFourChars} Campaign for {campaignStart:MMMM yyyy}",
                    Description = $"Description for campaign starting {campaignStart:MMMM yyyy}",
                    TargetRevenueAmount = (decimal)(10000 * Math.Ceiling((random.NextDouble() * 89) + 1)),
                    CampaignDateStart = campaignStart,
                    CampaignDateFinish = campaignEnd,
                    Status = status,
                    SalesTeamId = GetRandomValue(salesTeamIds, random)
                };

                await context.Campaign.AddAsync(campaign);
            }
        }

        await context.SaveChangesAsync();
    }

    private static CampaignStatus GetRandomStatus(Random random)
    {
        var statuses = new[] { CampaignStatus.Draft, CampaignStatus.Cancelled, CampaignStatus.Confirmed, CampaignStatus.OnProgress, CampaignStatus.OnHold, CampaignStatus.Finished, CampaignStatus.Archived };
        var weights = new[] { 1, 1, 10, 2, 1, 5, 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 CampaignStatus.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();
    }
}