using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace CMSMicroservice.Infrastructure.Services.Commission;

/// <summary>
/// Factory برای ایجاد Strategy مناسب براساس Config
/// </summary>
public class CommissionCalculationStrategyFactory : ICommissionCalculationStrategyFactory
{
    private readonly IApplicationDbContext _context;
    private readonly IWeekDefinitionRepository _weekRepository;
    private readonly IServiceProvider _serviceProvider;

    public CommissionCalculationStrategyFactory(
        IApplicationDbContext context,
        IWeekDefinitionRepository weekRepository,
        IServiceProvider serviceProvider)
    {
        _context = context;
        _weekRepository = weekRepository;
        _serviceProvider = serviceProvider;
    }

    /// <inheritdoc />
    public Task<ICommissionCalculationStrategy> CreateStrategyAsync(CancellationToken cancellationToken = default)
    {
        // خواندن Config از SystemConstants (استاتیک)
        var strategyValue = SystemConstants.CommissionCalculationStrategy.ToUpperInvariant();

        var strategyType = strategyValue switch
        {
            "SP" or "STOREDPROCEDURE" or "STORED_PROCEDURE" => CommissionCalculationStrategyType.StoredProcedure,
            _ => CommissionCalculationStrategyType.Orm
        };

        return Task.FromResult(CreateStrategy(strategyType));
    }

    /// <inheritdoc />
    public ICommissionCalculationStrategy CreateStrategy(CommissionCalculationStrategyType strategyType)
    {
        return strategyType switch
        {
            CommissionCalculationStrategyType.StoredProcedure => 
                new StoredProcedureCommissionCalculationStrategy(_context),
            
            _ => // Orm is default
                new OrmCommissionCalculationStrategy(_context, _weekRepository)
        };
    }
}
