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

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

public sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var query = db.MemberSummaryChangeLog.AsNoTracking().Include(x => x.Member).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 != 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.BeforeSummary != null && x.BeforeSummary.Contains(request.Keyword)),
                5 => query.Where(x => x.AfterSummary != null && x.AfterSummary.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,
                x.BeforeSummary,
                x.AfterSummary,
                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,
            BeforeSummary = x.BeforeSummary,
            AfterSummary = x.AfterSummary,
            IpAddress = x.IpAddress,
            CreatedAt = x.CreatedAt
        })
        .ToList();

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