using System.Data;
using Hangfire;
using Microsoft.Extensions.Logging;

namespace KArtSell.Modules.ModelOperations.Compliance;

/// <summary>
/// Command to process GDPR right-to-be-forgotten request.
/// </summary>
public class ProcessGdprRequestCommand
{
    public Guid TrackingId { get; set; } = Guid.NewGuid();
    public Guid CustomerId { get; set; }
    public DateTime RequestDate { get; set; }
    public string Reason { get; set; } = "Right to be forgotten (GDPR Article 17)";
    public Guid CorrelationId { get; set; }
}

/// <summary>
/// Handler to process GDPR requests asynchronously.
/// Queues Hangfire job for redaction (soft delete via JSONB anonymization).
/// </summary>
public class ProcessGdprRequestHandler
{
    private readonly IBackgroundJobClient _backgroundJobClient;
    private readonly ILogger<ProcessGdprRequestHandler> _logger;

    public ProcessGdprRequestHandler(
        IBackgroundJobClient backgroundJobClient,
        ILogger<ProcessGdprRequestHandler> logger)
    {
        _backgroundJobClient = backgroundJobClient;
        _logger = logger;
    }

    public async Task Handle(ProcessGdprRequestCommand request, CancellationToken ct)
    {
        try
        {
            // Queue Hangfire job for async GDPR redaction
            var jobId = _backgroundJobClient.Enqueue<GdprRedactionJob>(
                j => j.ExecuteAsync(
                    request.TrackingId,
                    request.CustomerId,
                    request.CorrelationId,
                    ct));

            _logger.LogInformation(
                "GDPR request {TrackingId} queued for customer {CustomerId}: job {JobId}",
                request.TrackingId, request.CustomerId, jobId);

            await Task.CompletedTask;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex,
                "Failed to queue GDPR request {TrackingId} for customer {CustomerId}",
                request.TrackingId, request.CustomerId);
            throw;
        }
    }
}

/// <summary>
/// Hangfire job to execute GDPR redaction (soft delete via anonymization).
/// Idempotent: Multiple executions safe (marks already-purged records).
/// </summary>
public class GdprRedactionJob
{
    private readonly IDbConnection _db;
    private readonly AuditSql _sql;
    private readonly ILogger<GdprRedactionJob> _logger;

    public GdprRedactionJob(
        IDbConnection db,
        AuditSql sql,
        ILogger<GdprRedactionJob> logger)
    {
        _db = db;
        _sql = sql;
        _logger = logger;
    }

    public async Task ExecuteAsync(
        Guid gdprTrackingId,
        Guid customerId,
        Guid correlationId,
        CancellationToken ct)
    {
        try
        {
            _logger.LogInformation(
                "Starting GDPR redaction for customer {CustomerId}, tracking {TrackingId}",
                customerId, gdprTrackingId);

            // Mark all pending GDPR retention records as PURGED
            await _sql.MarkGdprPurgedAsync(_db, customerId, ct);

            // Redact personal data in audit events (soft delete via JSONB)
            var pendingRetentions = await _sql.GetPendingGdprRetentionsAsync(_db, ct);
            var customerRetentions = pendingRetentions
                .Where(r => r.CustomerId == customerId)
                .ToList();

            foreach (var retention in customerRetentions)
            {
                await _sql.RedactAuditEventDetailsAsync(_db, retention.EventId, ct);
            }

            _logger.LogInformation(
                "GDPR redaction completed for customer {CustomerId}: {RedactedRecords} audit events anonymized",
                customerId, customerRetentions.Count);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex,
                "GDPR redaction failed for customer {CustomerId}, tracking {TrackingId}",
                customerId, gdprTrackingId);
            throw;
        }
    }
}
