/**
 * Cron: Rate-Limit Bucket GC — daily.
 *
 * Deletes `rate_limit_buckets` rows whose `refilled_at` is older than 7 days.
 * Stale buckets accumulate from one-shot IPs and abandoned clients; without
 * GC the table grows unboundedly and slows the rate-limit middleware's
 * SELECT/UPDATE path. Wrapped in `withSentry` per Phase A1 observability law.
 *
 * Phase D4 of rate-limit consolidation design.
 */

import { createDbService } from '@/server/services/db.js';
import { withSentry } from '@/server/observability/with-sentry';
import { purgeStale } from '../db/queries/rate-limits.js';
import type { CronEnv } from './deal-expiry.js';

export const runRateLimitGc = withSentry(
  async function runRateLimitGc(env: CronEnv): Promise<{ deleted: number }> {
    const db = env.db ?? createDbService({ DATABASE_URL: env.DATABASE_URL });
    const deleted = await purgeStale(db);
    return { deleted };
  },
  { name: 'rate-limit-gc', kind: 'cron' },
);
