using MemberCenter.Application.Abstractions;
using MemberCenter.Application.Models.Admin;
using MemberCenter.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;

namespace MemberCenter.Infrastructure.Services;

public sealed class AuditLogService : IAuditLogService
{
    private readonly MemberCenterDbContext _dbContext;

    public AuditLogService(MemberCenterDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<IReadOnlyList<AuditLogDto>> ListAsync(int take = 100)
    {
        var logs = await _dbContext.AuditLogs
            .OrderByDescending(l => l.CreatedAt)
            .Take(take)
            .ToListAsync();

        return logs
            .Select(l => new AuditLogDto(l.Id, l.ActorType, l.ActorId, l.Action, l.Payload.RootElement.GetRawText(), l.CreatedAt))
            .ToList();
    }
}
