using System.Net;
using System.Text.RegularExpressions;
using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Admin.Forum.Comment.Search;

public sealed partial class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    [GeneratedRegex("<[^>]*>")]
    private static partial Regex HtmlTagRegex();

    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var query = db.Comment.AsNoTracking().Include(c => c.Board).Include(c => c.Post).AsQueryable();

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

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

        if (!string.IsNullOrWhiteSpace(request.Keyword))
        {
            var kw = request.Keyword.Trim();
            query = request.Search switch
            {
                0 => query.Where(c => c.Content.Contains(kw)),
                1 => query.Where(c => (c.Name != null && c.Name.Contains(kw)) || (c.SID != null && c.SID.Contains(kw))),
                _ => query.Where(c => c.Content.Contains(kw))
            };
        }

        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));
        }

        if (request.IsDeleted == true)
        {
            query = query.Where(c => c.IsDeleted);
        }

        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.BoardID,
                BoardName = c.Board.Name,
                c.PostID,
                PostSubject = c.Post.Subject,
                c.Content,
                c.Name,
                c.SID,
                c.IsReply,
                c.IsSecret,
                c.IsDeleted,
                c.Likes,
                c.Dislikes,
                c.Reports,
                c.Replies,
                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.BoardID,
                c.BoardName,
                c.PostID,
                c.PostSubject,
                StripHtml(c.Content),
                c.Name,
                c.SID,
                c.IsReply,
                c.IsSecret,
                c.IsDeleted,
                c.Likes,
                c.Dislikes,
                c.Reports,
                c.Replies,
                c.UpdatedAt,
                c.CreatedAt
            ))]
        );
    }

    private static string StripHtml(string html)
    {
        if (string.IsNullOrEmpty(html))
        {
            return html;
        }

        var decoded = WebUtility.HtmlDecode(html);
        return HtmlTagRegex().Replace(decoded, "");
    }
}