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

namespace Application.Features.Admin.Channel.List.Search;

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

        if (!string.IsNullOrWhiteSpace(request.Keyword))
        {
            var kw = request.Keyword.Trim();
            query = request.Search switch
            {
                1 => query.Where(c => c.Name.Contains(kw)),
                2 => query.Where(c => c.SID.Contains(kw)),
                3 => query.Where(c => c.Handle != null && c.Handle.Contains(kw)),
                4 => query.Where(c => c.YouTubeUrl.Contains(kw)),
                5 => query.Where(c => c.MemberID.ToString().Contains(kw)),
                6 => query.Where(c => c.Member.Email.Contains(kw)),
                7 => query.Where(c => c.Member.Name != null && c.Member.Name.Contains(kw)),
                _ => query.Where(c => c.Name.Contains(kw))
            };
        }

        if (request.IsVerified.HasValue)
        {
            query = query.Where(c => c.IsVerified == request.IsVerified.Value);
        }

        if (!string.IsNullOrWhiteSpace(request.StartAt) && DateTime.TryParse(request.StartAt, out var startDate))
        {
            query = query.Where(c => c.CreatedAt >= startDate);
        }

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

        query = query.OrderByDescending(c => c.ID);

        var total = await query.CountAsync(ct);

        var list = await query
            .Skip((request.PageNum - 1) * request.PerPage)
            .Take(request.PerPage)
            .Select(c => new
            {
                c.ID,
                c.SID,
                c.Name,
                c.Handle,
                c.YouTubeUrl,
                c.PlatformFeeRate,
                c.IsVerified,
                c.IsActive,
                c.MemberID,
                MemberName = c.Member.Name,
                MemberEmail = c.Member.Email,
                c.UpdatedAt,
                c.CreatedAt
            })
            .ToListAsync(ct);

        var startNum = total - ((request.PageNum - 1) * request.PerPage);

        return new Response(
            total,
            [..list.Select((c, i) => new Response.Row(
                Num: startNum - i,
                c.ID,
                c.SID,
                c.Name,
                c.Handle,
                c.YouTubeUrl,
                c.PlatformFeeRate,
                c.IsVerified,
                c.IsActive,
                c.MemberID,
                c.MemberName,
                c.MemberEmail,
                c.UpdatedAt,
                c.CreatedAt
            ))]
        );
    }
}