using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Data.Entities;
using Indotalent.Infrastructure.Database;
using Indotalent.Shared.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Serilogs.Database;

public record GetSerilogLogsPagedListResponse(
    int Id,
    string? Message,
    string? Level,
    DateTimeOffset TimeStamp,
    string? Exception)
{
    public GetSerilogLogsPagedListResponse() : this(0, null, null, DateTimeOffset.Now, null) { }
}

public record GetSerilogLogsPagedListQuery(ApiRequest Request) : IRequest<PagedList<GetSerilogLogsPagedListResponse>>;

public class GetSerilogLogsPagedListHandler : IRequestHandler<GetSerilogLogsPagedListQuery, PagedList<GetSerilogLogsPagedListResponse>>
{
    private readonly AppDbContext _context;

    public GetSerilogLogsPagedListHandler(AppDbContext context)
    {
        _context = context;
    }

    public async Task<PagedList<GetSerilogLogsPagedListResponse>> Handle(GetSerilogLogsPagedListQuery query, CancellationToken cancellationToken)
    {
        var r = query.Request;
        var queryable = _context.Set<SerilogLogs>().AsNoTracking();

        if (!string.IsNullOrEmpty(r.SearchTerm))
        {
            queryable = queryable.Where(x => x.Message.Contains(r.SearchTerm) || x.Level.Contains(r.SearchTerm));
        }

        var pagedList = await queryable
            .OrderByDescending(x => x.TimeStamp)
            .Select(x => new GetSerilogLogsPagedListResponse(
                x.Id,
                x.Message,
                x.Level,
                x.TimeStamp,
                x.Exception))
            .ToPagedListAsync(r.Skip, r.Top);

        return pagedList;
    }
}