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

namespace Indotalent.Infrastructure.Database.Demo;

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

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

        var confirmedCampaigns = await context.Campaign
            .Where(c => c.Status == CampaignStatus.Confirmed)
            .Select(c => c.Id)
            .ToListAsync();

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

        if (!confirmedCampaigns.Any() || !salesTeamIds.Any()) return;

        var closingStatusValues = Enum.GetValues(typeof(ClosingStatus)).Cast<ClosingStatus>().ToList();

        var pipelineStageCounts = new Dictionary<PipelineStage, int>
        {
            { PipelineStage.Prospecting, 80 },
            { PipelineStage.Qualification, 70 },
            { PipelineStage.NeedAnalysis, 60 },
            { PipelineStage.Proposal, 50 },
            { PipelineStage.Negotiation, 40 },
            { PipelineStage.DecisionMaking, 30 },
            { PipelineStage.Closed, 15 }
        };

        foreach (var stage in pipelineStageCounts)
        {
            for (int i = 0; i < stage.Value; i++)
            {
                var prospectingDate = GetRandomDate(dateStart, dateFinish, random);
                var closingEstimation = prospectingDate.AddDays(random.Next(30, 90));
                var closingActual = closingEstimation.AddDays(random.Next(-10, 11));

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

                var lead = new Lead
                {
                    AutoNumber = autoNo,
                    Title = $"Lead from {prospectingDate:MMMM yyyy}",
                    Description = $"Lead description for {prospectingDate:MMMM yyyy}",
                    CompanyName = $"Company Name {random.Next(1000, 9999)}",
                    CompanyDescription = "Sample company description",
                    CompanyAddressStreet = "123 Main St",
                    CompanyAddressCity = "Anytown",
                    CompanyAddressState = "State",
                    CompanyAddressZipCode = "12345",
                    CompanyAddressCountry = "Country",
                    CompanyPhoneNumber = $"+1{random.Next(100, 999)}-{random.Next(100, 999)}-{random.Next(1000, 9999)}",
                    CompanyFaxNumber = $"+1{random.Next(100, 999)}-{random.Next(100, 999)}-{random.Next(1000, 9999)}",
                    CompanyEmail = $"info{random.Next(1000, 9999)}@company.com",
                    CompanyWebsite = $"www.company{random.Next(1000, 9999)}.com",
                    CompanyWhatsApp = $"+1{random.Next(100, 999)}-{random.Next(100, 999)}-{random.Next(1000, 9999)}",
                    CompanyLinkedIn = $"linkedin.com/company{random.Next(1000, 9999)}",
                    CompanyFacebook = $"facebook.com/company{random.Next(1000, 9999)}",
                    CompanyInstagram = $"instagram.com/company{random.Next(1000, 9999)}",
                    CompanyTwitter = $"twitter.com/company{random.Next(1000, 9999)}",
                    DateProspecting = prospectingDate,
                    DateClosingEstimation = closingEstimation,
                    DateClosingActual = closingActual,
                    AmountTargeted = (decimal)(10000 * Math.Ceiling((random.NextDouble() * 89) + 1)),
                    AmountClosed = (decimal)(10000 * Math.Ceiling((random.NextDouble() * 89) + 1)),
                    BudgetScore = (decimal)(10.0 * Math.Ceiling(random.NextDouble() * 10)),
                    AuthorityScore = (decimal)(10.0 * Math.Ceiling(random.NextDouble() * 10)),
                    NeedScore = (decimal)(10.0 * Math.Ceiling(random.NextDouble() * 10)),
                    TimelineScore = (decimal)(10.0 * Math.Ceiling(random.NextDouble() * 10)),
                    PipelineStage = stage.Key,
                    ClosingStatus = closingStatusValues[random.Next(closingStatusValues.Count)],
                    ClosingNote = "Sample closing note",
                    CampaignId = GetRandomValue(confirmedCampaigns, random),
                    SalesTeamId = GetRandomValue(salesTeamIds, random)
                };

                await context.Lead.AddAsync(lead);
            }
        }

        await context.SaveChangesAsync();
    }

    private static DateTime GetRandomDate(DateTime startDate, DateTime endDate, Random random)
    {
        var range = (endDate - startDate).Days;
        return startDate.AddDays(random.Next(range));
    }

    private static string GetRandomValue(List<string> list, Random random)
    {
        return list[random.Next(list.Count)];
    }
}