using CMSMicroservice.Domain.Events;
using CMSMicroservice.Domain.Enums;
using CMSMicroservice.Application.DayaLoanCQ.Services;
using Microsoft.Extensions.Logging;

namespace CMSMicroservice.Application.DayaLoanCQ.Commands.CheckDayaLoanStatus;

public class CheckDayaLoanStatusCommandHandler : IRequestHandler<CheckDayaLoanStatusCommand, CheckDayaLoanStatusResponseDto>
{
    private readonly IApplicationDbContext _context;
    private readonly IDayaLoanApiService _dayaApiService;
    private readonly ILogger<CheckDayaLoanStatusCommandHandler> _logger;

    public CheckDayaLoanStatusCommandHandler(
        IApplicationDbContext context,
        IDayaLoanApiService dayaApiService,
        ILogger<CheckDayaLoanStatusCommandHandler> logger)
    {
        _context = context;
        _dayaApiService = dayaApiService;
        _logger = logger;
    }

    public async Task<CheckDayaLoanStatusResponseDto> Handle(CheckDayaLoanStatusCommand request, CancellationToken cancellationToken)
    {
        var results = new List<DayaLoanStatusItem>();
        
        try
        {
            // فراخوانی سرویس دایا (Mock یا Real)
            var dayaResults = await _dayaApiService.CheckLoanStatusAsync(request.NationalCodes, cancellationToken);
            
            foreach (var dayaResult in dayaResults)
            {
                try
                {
                    results.Add(new DayaLoanStatusItem
                    {
                        NationalCode = dayaResult.NationalCode,
                        Status = dayaResult.Status,
                        ContractNumber = dayaResult.ContractNumber,
                        Message = "استعلام موفق"
                    });
                    
                    // ذخیره یا به‌روزرسانی در دیتابیس
                    var existingContract = await _context.DayaLoanContracts
                        .FirstOrDefaultAsync(d => d.NationalCode == dayaResult.NationalCode, cancellationToken);
                    
                    if (existingContract != null)
                    {
                        existingContract.LastCheckDate = DateTime.UtcNow;
                        existingContract.Status = dayaResult.Status;
                        existingContract.ContractNumber = dayaResult.ContractNumber;
                    }
                    else
                    {
                        var user = await _context.Users
                            .FirstOrDefaultAsync(u => u.NationalCode == dayaResult.NationalCode, cancellationToken);
                        
                        if (user != null)
                        {
                            var newContract = new DayaLoanContract
                            {
                                UserId = user.Id,
                                NationalCode = dayaResult.NationalCode,
                                Status = dayaResult.Status,
                                ContractNumber = dayaResult.ContractNumber,
                                LastCheckDate = DateTime.UtcNow,
                                IsProcessed = false
                            };
                            
                            await _context.DayaLoanContracts.AddAsync(newContract, cancellationToken);
                        }
                    }
                    
                    await _context.SaveChangesAsync(cancellationToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error processing Daya result for {NationalCode}", dayaResult.NationalCode);
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error calling Daya API service");
            
            // در صورت خطا، نتایج خالی برمی‌گردانیم
            foreach (var nationalCode in request.NationalCodes)
            {
                results.Add(new DayaLoanStatusItem
                {
                    NationalCode = nationalCode,
                    Status = DayaLoanStatus.PendingReceive,
                    ContractNumber = null,
                    Message = $"خطا در استعلام: {ex.Message}"
                });
            }
        }
        
        return new CheckDayaLoanStatusResponseDto
        {
            Results = results,
            TotalChecked = request.NationalCodes.Count,
            SuccessCount = results.Count(r => r.ContractNumber != null)
        };
    }
}
