using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.Extensions.Logging;

namespace CMSMicroservice.Application.ConfigurationCQ.Commands.SeedVATConfiguration;

/// <summary>
/// Seed initial VAT configuration
/// نرخ مالیات پیش‌فرض ۹٪
/// </summary>
public class SeedVATConfigurationCommand : IRequest<Unit>
{
}

public class SeedVATConfigurationCommandHandler : IRequestHandler<SeedVATConfigurationCommand, Unit>
{
    private readonly IApplicationDbContext _context;
    private readonly ILogger<SeedVATConfigurationCommandHandler> _logger;

    public SeedVATConfigurationCommandHandler(
        IApplicationDbContext context,
        ILogger<SeedVATConfigurationCommandHandler> logger)
    {
        _context = context;
        _logger = logger;
    }

    public async Task<Unit> Handle(SeedVATConfigurationCommand request, CancellationToken cancellationToken)
    {
        var configs = new[]
        {
            new
            {
                Scope = ConfigurationScope.VAT,
                Key = "Rate",
                Value = "0.09",
                Description = "نرخ مالیات بر ارزش افزوده (۹٪)"
            },
            new
            {
                Scope = ConfigurationScope.VAT,
                Key = "IsEnabled",
                Value = "true",
                Description = "فعال/غیرفعال بودن محاسبه مالیات"
            }
        };

        foreach (var config in configs)
        {
            var exists = _context.SystemConfigurations
                .Any(x => x.Scope == config.Scope && x.Key == config.Key);

            if (!exists)
            {
                _context.SystemConfigurations.Add(new Domain.Entities.Configuration.SystemConfiguration
                {
                    Scope = config.Scope,
                    Key = config.Key,
                    Value = config.Value,
                    Description = config.Description
                });

                _logger.LogInformation(
                    "VAT configuration seeded: {Scope}.{Key} = {Value}",
                    config.Scope,
                    config.Key,
                    config.Value
                );
            }
        }

        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
