using Microsoft.Extensions.Logging;
using RealCV.Application.Interfaces;
using RealCV.Domain.Entities;
using RealCV.Infrastructure.Data;

namespace RealCV.Infrastructure.Services;

public sealed class AuditService : IAuditService
{
    private readonly ApplicationDbContext _dbContext;
    private readonly ILogger<AuditService> _logger;

    public AuditService(ApplicationDbContext dbContext, ILogger<AuditService> logger)
    {
        _dbContext = dbContext;
        _logger = logger;
    }

    public async Task LogAsync(
        Guid userId,
        string action,
        string? entityType = null,
        Guid? entityId = null,
        string? details = null,
        string? ipAddress = null)
    {
        var auditLog = new AuditLog
        {
            Id = Guid.NewGuid(),
            UserId = userId,
            Action = action,
            EntityType = entityType,
            EntityId = entityId,
            Details = details,
            IpAddress = ipAddress,
            CreatedAt = DateTime.UtcNow
        };

        _dbContext.AuditLogs.Add(auditLog);

        try
        {
            await _dbContext.SaveChangesAsync();
            _logger.LogDebug("Audit log created: {Action} by user {UserId}", action, userId);
        }
        catch (Exception ex)
        {
            // Don't let audit failures break the main flow
            _logger.LogError(ex, "Failed to create audit log: {Action} by user {UserId}", action, userId);
        }
    }
}
