using Application.Abstractions.Messaging;
using Application.Abstractions.Data;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Admin.Member.Logs.IntroChange.Search;

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

        // Search filtering
        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 != null && x.Member.Email.Contains(request.Keyword)),
                3 => query.Where(x => x.Member != null && x.Member.Name != null && x.Member.Name.Contains(request.Keyword)),
                4 => query.Where(x => x.BeforeIntro != null && x.BeforeIntro.Contains(request.Keyword)),
                5 => query.Where(x => x.AfterIntro != null && x.AfterIntro.Contains(request.Keyword)),
                _ => query
            };
        }

        // Date filtering
        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.Email,
                x.BeforeIntro,
                x.AfterIntro,
                x.IpAddress,
                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,
            BeforeIntro = x.BeforeIntro,
            AfterIntro = x.AfterIntro,
            IpAddress = x.IpAddress,
            CreatedAt = x.CreatedAt
        })
        .ToList();

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