using Microsoft.EntityFrameworkCore;
using Meezi.Infrastructure.Data;

namespace Meezi.API.Jobs;

/// <summary>
/// Purges old idempotency records. Keys only need to outlive realistic offline
/// gaps and client retries, so a short retention keeps the table small.
/// </summary>
public class IdempotencyCleanupJob
{
    private static readonly TimeSpan Retention = TimeSpan.FromDays(7);

    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ILogger<IdempotencyCleanupJob> _logger;

    public IdempotencyCleanupJob(
        IServiceScopeFactory scopeFactory,
        ILogger<IdempotencyCleanupJob> logger)
    {
        _scopeFactory = scopeFactory;
        _logger = logger;
    }

    public async Task ExecuteAsync()
    {
        await using var scope = _scopeFactory.CreateAsyncScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        var cutoff = DateTime.UtcNow - Retention;
        var removed = await db.IdempotencyRecords
            .Where(r => r.CreatedAt < cutoff)
            .ExecuteDeleteAsync();
        if (removed > 0)
            _logger.LogInformation("Purged {Count} idempotency records older than {Days}d", removed, Retention.TotalDays);
    }
}
