using Dapper;
using Npgsql;
using Kbx.Shared.ExternalData.Generated;

namespace Kbx.Shared.ExternalData;

public sealed class KbxExternalDataRetentionJob(NpgsqlDataSource dataSource)
{
    public async Task RunAsync(CancellationToken ct)
    {
        await using var connection=await dataSource.OpenConnectionAsync(ct);
        foreach(var dataset in KbxExternalDataCatalog.All.Values)
        {
            var before=DateTimeOffset.UtcNow.AddDays(-dataset.NormalizedRetentionDays);
            const string sql="delete from kbx.external_data_observations where dataset_id=@DatasetId and ingested_at < @Before";
            await connection.ExecuteAsync(new CommandDefinition(sql,new{DatasetId=dataset.Id,Before=before},cancellationToken:ct));
        }
    }
}
