using Microsoft.EntityFrameworkCore;
using PowderCoating.Core.Entities;
using PowderCoating.Core.Interfaces.Services;
using PowderCoating.Infrastructure.Data;

namespace PowderCoating.Infrastructure.Services;

/// <summary>
/// Concrete implementation of <see cref="IAuditLogService"/> that writes <see cref="AuditLog"/>
/// entries via <see cref="ApplicationDbContext"/> directly. <c>AuditLog</c> does not inherit
/// from <c>BaseEntity</c> so it cannot be managed through the generic repository; this service
/// owns that write path and keeps <c>ApplicationDbContext</c> out of controller constructors.
/// </summary>
public class AuditLogService : IAuditLogService
{
    private readonly ApplicationDbContext _context;

    public AuditLogService(ApplicationDbContext context)
    {
        _context = context;
    }

    /// <inheritdoc/>
    public async Task LogAsync(AuditLog entry)
    {
        _context.AuditLogs.Add(entry);
        await _context.SaveChangesAsync();
    }

    /// <inheritdoc/>
    public async Task<List<AuditLog>> GetUserActivityAsync(string userId, int limit = 50)
    {
        return await _context.AuditLogs
            .AsNoTracking()
            .Where(l => l.UserId == userId && l.EntityType == "ApplicationUser")
            .OrderByDescending(l => l.Timestamp)
            .Take(limit)
            .ToListAsync();
    }
}
