using Indotalent.Data.Entities;
using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Serilogs.Database;

public record GetSerilogLogsByIdResponse(
    int Id,
    string? Message,
    string? MessageTemplate,
    string? Level,
    DateTimeOffset TimeStamp,
    string? Exception,
    string? Properties);

public record GetSerilogLogsByIdQuery(int Id) : IRequest<GetSerilogLogsByIdResponse?>;

public class GetSerilogLogsByIdHandler : IRequestHandler<GetSerilogLogsByIdQuery, GetSerilogLogsByIdResponse?>
{
    private readonly AppDbContext _context;

    public GetSerilogLogsByIdHandler(AppDbContext context) => _context = context;

    public async Task<GetSerilogLogsByIdResponse?> Handle(GetSerilogLogsByIdQuery request, CancellationToken cancellationToken)
    {
        return await _context.Set<SerilogLogs>()
            .AsNoTracking()
            .Where(x => x.Id == request.Id)
            .Select(x => new GetSerilogLogsByIdResponse(
                x.Id, x.Message, x.MessageTemplate, x.Level, x.TimeStamp, x.Exception, x.Properties))
            .FirstOrDefaultAsync(cancellationToken);
    }
}
