using Dapper;
using SIGCM.Domain.Entities;
using SIGCM.Infrastructure.Data;

namespace SIGCM.Infrastructure.Repositories;

public class AuditRepository
{
  private readonly IDbConnectionFactory _db;
  public AuditRepository(IDbConnectionFactory db) => _db = db;

  public async Task AddLogAsync(AuditLog log)
  {
    using var conn = _db.CreateConnection();
    var sql = @"INSERT INTO AuditLogs (UserId, Action, EntityId, EntityType, Details) 
                    VALUES (@UserId, @Action, @EntityId, @EntityType, @Details)";
    await conn.ExecuteAsync(sql, log);
  }

  public async Task<IEnumerable<AuditLog>> GetRecentLogsAsync(int limit = 50)
  {
    using var conn = _db.CreateConnection();
    var sql = @"SELECT TOP (@Limit) a.*, u.Username 
                    FROM AuditLogs a
                    JOIN Users u ON a.UserId = u.Id
                    ORDER BY a.CreatedAt DESC";
    return await conn.QueryAsync<AuditLog>(sql, new { Limit = limit });
  }

  public async Task<IEnumerable<AuditLog>> GetLogsByUserAsync(int userId, int limit = 20)
  {
    using var conn = _db.CreateConnection();
    var sql = @"SELECT TOP (@Limit) a.*, u.Username 
                FROM AuditLogs a
                JOIN Users u ON a.UserId = u.Id
                WHERE a.UserId = @UserId
                ORDER BY a.CreatedAt DESC";
    return await conn.QueryAsync<AuditLog>(sql, new { UserId = userId, Limit = limit });
  }

  public async Task<IEnumerable<AuditLog>> GetFilteredLogsAsync(DateTime from, DateTime to, int? userId = null)
  {
    using var conn = _db.CreateConnection();
    var sql = @"SELECT a.*, u.Username 
                FROM AuditLogs a
                JOIN Users u ON a.UserId = u.Id
                WHERE a.CreatedAt >= @From AND a.CreatedAt <= @To";

    if (userId.HasValue) sql += " AND a.UserId = @UserId";

    sql += " ORDER BY a.CreatedAt DESC";

    return await conn.QueryAsync<AuditLog>(sql, new { From = from, To = to, UserId = userId });
  }
}