using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using CMSMicroservice.Domain.Entities.Configuration;
using CMSMicroservice.Domain.Enums;
using System.Collections.Generic;

namespace CMSMicroservice.Infrastructure.Persistence;

public  class ApplicationDbContextInitialiser
{
    private readonly ApplicationDbContext _context;
    private readonly ILogger<ApplicationDbContextInitialiser> _logger;

    public ApplicationDbContextInitialiser(ApplicationDbContext context, ILogger<ApplicationDbContextInitialiser> logger)
    {
        _context = context;
        _logger = logger;
    }

    public async Task InitialiseAsync()
    {
        try
        {
            if (_context.Database.IsSqlServer())
            {
                await _context.Database.MigrateAsync();
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An error occurred while initialising the database.");
            throw;
        }
    }

    public async Task SeedAsync()
    {
        try
        {
            await TrySeedAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An error occurred while seeding the database.");
            throw;
        }
    }
    public async Task TrySeedAsync()
    {
        // Seed / upsert default System Configurations for Network-Club-Commission System
        var desiredConfigurations = new List<SystemConfiguration>
        {
            // Network Configuration
            new SystemConfiguration
            {
                Key = "Network.MaxNetworkDepth",
                Value = "15",
                Description = "حداکثر عمق شبکه باینری",
                Scope = ConfigurationScope.Network,
                IsActive = true
            },
            new SystemConfiguration
            {
                Key = "Network.MaxChildrenPerLeg",
                Value = "1",
                Description = "حداکثر تعداد فرزند مستقیم در هر پا",
                Scope = ConfigurationScope.Network,
                IsActive = true
            },

            // Commission Configuration
            new SystemConfiguration
            {
                Key = "Commission.MaxWeeklyBalancesPerLeg",
                Value = "300",
                Description = "سقف تعادل هفتگی برای هر دست (چپ یا راست) - حداکثر کل = 600",
                Scope = ConfigurationScope.Commission,
                IsActive = true
            },
            new SystemConfiguration
            {
                Key = "Commission.MaxNetworkLevel",
                Value = "15",
                Description = "حداکثر عمق شبکه برای محاسبه کمیسیون (تعداد لول زیرمجموعه)",
                Scope = ConfigurationScope.Commission,
                IsActive = true
            },
            new SystemConfiguration
            {
                Key = "Commission.MinWithdrawalAmount",
                Value = "1000000",
                Description = "حداقل مبلغ برداشت (ریال)",
                Scope = ConfigurationScope.Commission,
                IsActive = true
            },
            new SystemConfiguration
            {
                Key = "Commission.DefaultInitialContribution",
                Value = "25000000",
                Description = "مبلغ پیش‌فرض مشارکت/هزینه فعال‌سازی",
                Scope = ConfigurationScope.Commission,
                IsActive = true
            },
            new SystemConfiguration
            {
                Key = "Commission.WeeklyPoolContributionPercent",
                Value = "20",
                Description = "درصد مشارکت در استخر هفتگی از کل فعال‌سازی‌های جدید شبکه (20%)",
                Scope = ConfigurationScope.Commission,
                IsActive = true
            },

            // Club Configuration
            new SystemConfiguration
            {
                Key = "Club.ActivationFee",
                Value = "25000000",
                Description = "هزینه فعال‌سازی عضویت باشگاه (ریال)",
                Scope = ConfigurationScope.Club,
                IsActive = true
            },
            new SystemConfiguration
            {
                Key = "Club.MembershipGiftValue",
                Value = "25200000",
                Description = "مبلغ هدیه حق عضویت باشگاه (ریال) - این مبلغ از کیف پول کم نمی‌شود",
                Scope = ConfigurationScope.Club,
                IsActive = true
            },

            // System Configuration
            new SystemConfiguration
            {
                Key = "System.EnableAuditLog",
                Value = "true",
                Description = "فعال‌سازی لاگ تغییرات",
                Scope = ConfigurationScope.System,
                IsActive = true
            }
        };

        var existingKeys = _context.SystemConfigurations
            .Select(c => c.Key)
            .ToHashSet(StringComparer.OrdinalIgnoreCase);

        var newConfigs = desiredConfigurations
            .Where(c => !existingKeys.Contains(c.Key))
            .ToList();

        if (newConfigs.Any())
        {
            await _context.SystemConfigurations.AddRangeAsync(newConfigs);
            await _context.SaveChangesAsync();
            _logger.LogInformation("Seeded {Count} default system configurations", newConfigs.Count);
        }
    }
}
