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

namespace CMSMicroservice.Application.CommissionCQ.Queries.GetMyCommissionPayouts;

public class GetMyCommissionPayoutsQueryHandler : IRequestHandler<GetMyCommissionPayoutsQuery, GetMyCommissionPayoutsResponseDto>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

    public GetMyCommissionPayoutsQueryHandler(
        IApplicationDbContext context,
        ICurrentUserService currentUser)
    {
        _context = context;
        _currentUser = currentUser;
    }

    public async Task<GetMyCommissionPayoutsResponseDto> Handle(GetMyCommissionPayoutsQuery request, CancellationToken cancellationToken)
    {
        // دریافت UserId از JWT (فقط برای Customer API)
        if (!long.TryParse(_currentUser.UserId, out var userId))
        {
            throw new UnauthorizedAccessException("User not authenticated");
        }

        var query = _context.UserCommissionPayouts
            .Include(x => x.WeekDefinition)
            .Include(x => x.Package)
            .Where(x => x.UserId == userId)
            .AsNoTracking()
            .AsQueryable();

        // فیلترها
        if (request.Status.HasValue)
        {
            query = query.Where(x => x.Status == request.Status.Value);
        }

        if (request.WeekDefinitionId.HasValue)
        {
            query = query.Where(x => x.WeekDefinitionId == request.WeekDefinitionId.Value);
        }

        // فیلتر بر اساس پکیج
        if (request.PackageId.HasValue && request.PackageId.Value > 0)
        {
            query = query.Where(x => x.PackageId == request.PackageId.Value);
        }

        // مرتب‌سازی: جدیدترین اول
        query = query.OrderByDescending(x => x.Created);

        var meta = await query.GetMetaData(request.PaginationState, cancellationToken);

        var models = await query
            .PaginatedListAsync(paginationState: request.PaginationState)
            .Select(x => new GetMyCommissionPayoutsResponseModel
            {
                Id = x.Id,
                WeekDefinitionId = x.WeekDefinitionId,
                WeekDisplayName = x.WeekDefinition != null ? x.WeekDefinition.DisplayName : "",
                BalancesEarned = x.BalancesEarned,
                TotalAmount = x.TotalAmount,
                AmountFormatted = x.TotalAmount.ToString("N0") + " تومان",
                Status = x.Status,
                CalculatedDate = x.PaidAt ?? (DateTime?)x.Created,
                DatePersian = "",
                PackageId = x.PackageId,
                PackageTitle = x.Package != null ? x.Package.Title : ""
            })
            .ToListAsync(cancellationToken);

        return new GetMyCommissionPayoutsResponseDto
        {
            MetaData = meta,
            Models = models
        };
    }
}
