using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.CommissionCQ.Commands.CalculateWeeklyBalances;
using CMSMicroservice.Application.CommissionCQ.Commands.CalculateWeeklyCommissionPool;
using CMSMicroservice.Application.CommissionCQ.Commands.ProcessUserPayouts;

namespace CMSMicroservice.Application.CommissionCQ.Commands.TriggerWeeklyCalculation;

public class TriggerWeeklyCalculationCommandHandler : IRequestHandler<TriggerWeeklyCalculationCommand, TriggerWeeklyCalculationResponseDto>
{
    private readonly IApplicationDbContext _context;
    private readonly IMediator _mediator;

    public TriggerWeeklyCalculationCommandHandler(
        IApplicationDbContext context,
        IMediator mediator)
    {
        _context = context;
        _mediator = mediator;
    }

    public async Task<TriggerWeeklyCalculationResponseDto> Handle(
        TriggerWeeklyCalculationCommand request, 
        CancellationToken cancellationToken)
    {
        var executionId = Guid.NewGuid().ToString();
        var startedAt = DateTime.UtcNow;

        try
        {
            // Validate week number format
            if (string.IsNullOrWhiteSpace(request.WeekNumber))
            {
                return new TriggerWeeklyCalculationResponseDto
                {
                    Success = false,
                    Message = "شماره هفته نمی‌تواند خالی باشد",
                    ExecutionId = executionId,
                    StartedAt = startedAt
                };
            }

            var steps = new List<string>();

            // Step 1: Calculate Weekly Balances
            if (!request.SkipBalances)
            {
                await _mediator.Send(new CalculateWeeklyBalancesCommand
                {
                    WeekNumber = request.WeekNumber,
                    ForceRecalculate = request.ForceRecalculate
                }, cancellationToken);
                steps.Add("محاسبه امتیازات هفتگی");
            }

            // Step 2: Calculate Weekly Commission Pool
            if (!request.SkipPool)
            {
                await _mediator.Send(new CalculateWeeklyCommissionPoolCommand
                {
                    WeekNumber = request.WeekNumber
                }, cancellationToken);
                steps.Add("محاسبه استخر کمیسیون");
            }

            // Step 3: Process User Payouts
            if (!request.SkipPayouts)
            {
                await _mediator.Send(new ProcessUserPayoutsCommand
                {
                    WeekNumber = request.WeekNumber,
                    ForceReprocess = request.ForceRecalculate
                }, cancellationToken);
                steps.Add("پردازش پرداخت‌های کاربران");
            }

            return new TriggerWeeklyCalculationResponseDto
            {
                Success = true,
                Message = $"محاسبات هفته {request.WeekNumber} با موفقیت انجام شد. مراحل: {string.Join(", ", steps)}",
                ExecutionId = executionId,
                StartedAt = startedAt
            };
        }
        catch (Exception ex)
        {
            return new TriggerWeeklyCalculationResponseDto
            {
                Success = false,
                Message = $"خطا در اجرای محاسبات: {ex.Message}",
                ExecutionId = executionId,
                StartedAt = startedAt
            };
        }
    }
}
