using Application.Abstractions.Messaging;
using Application.Abstractions.Data;
using Domain.Entities.Wallets.ValueObject;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Admin.Member.Wallet.List.Search;

public sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var query = db.Wallet.AsNoTracking().Include(x => x.Member).Include(x => x.Balances).AsQueryable();

        // 키워드 검색
        if (!string.IsNullOrWhiteSpace(request.Keyword))
        {
            query = request.Search switch
            {
                1 => query.Where(x => x.MemberID.ToString().Contains(request.Keyword)),
                2 => query.Where(x => x.Member.Name != null && x.Member.Name.Contains(request.Keyword)),
                3 => query.Where(x => x.Member.Email.Contains(request.Keyword)),
                4 => query.Where(x => x.ID.ToString().Contains(request.Keyword)),
                _ => query
            };
        }

        // 날짜 필터
        if (!string.IsNullOrWhiteSpace(request.StartAt) && DateTime.TryParse(request.StartAt, out var startAt))
        {
            query = query.Where(x => x.CreatedAt >= startAt);
        }

        if (!string.IsNullOrWhiteSpace(request.EndAt) && DateTime.TryParse(request.EndAt, out var endAt))
        {
            query = query.Where(x => x.CreatedAt <= endAt);
        }

        var total = await query.CountAsync(ct);
        var skip = (request.PageNum - 1) * request.PerPage;

        var list = await query.OrderByDescending(x => x.ID).Skip(skip).Take(request.PerPage).Select(x => new
        {
            x.ID, x.MemberID,
            MemberEmail = x.Member.Email,
            MemberName = x.Member.Name,
            Balances = x.Balances,
            x.UpdatedAt, x.CreatedAt
        }).ToListAsync(ct);

        var rows = list.Select((x, idx) => new Response.Row
        {
            Num = total - skip - idx,
            ID = x.ID,
            MemberID = x.MemberID,
            MemberEmail = x.MemberEmail,
            MemberName = x.MemberName,
            Balance = (long)x.Balances.Where(b => b.Type != WalletBalanceType.Locked).Sum(b => b.Amount.Value),
            DonationBalance = (long)(x.Balances.FirstOrDefault(b => b.Type == WalletBalanceType.Donation)?.Amount.Value ?? 0),
            UpdatedAt = x.UpdatedAt,
            CreatedAt = x.CreatedAt
        }).ToList();

        return new Response
        {
            Total = total,
            List = rows
        };
    }
}