import type { DrizzleClient } from '@/server/db/client.js';
import { cronRuns } from '@/server/db/schema.js';
import type { CronRunRecord } from '@/server/db/schema.js';
import { scrubStringValue } from '@/server/observability/pii-scrub.js';

/** Record a successful cron handler run (UPSERT, sets expected interval if new). */
export async function recordCronSuccess(
  db: DrizzleClient,
  cronKey: string,
  expectedIntervalMinutes: number,
  now: Date,
): Promise<void> {
  await db
    .insert(cronRuns)
    .values({ cronKey, lastSuccessAt: now, expectedIntervalMinutes })
    .onConflictDoUpdate({
      target: cronRuns.cronKey,
      set: { lastSuccessAt: now, expectedIntervalMinutes },
    });
}

/** Record a failed cron handler run (UPSERT; does NOT touch last_success_at). */
export async function recordCronError(
  db: DrizzleClient,
  cronKey: string,
  expectedIntervalMinutes: number,
  errorMessage: string,
  now: Date,
): Promise<void> {
  const scrubbed = scrubStringValue(errorMessage).slice(0, 500);
  await db
    .insert(cronRuns)
    .values({ cronKey, lastErrorAt: now, lastError: scrubbed, expectedIntervalMinutes })
    .onConflictDoUpdate({
      target: cronRuns.cronKey,
      set: { lastErrorAt: now, lastError: scrubbed, expectedIntervalMinutes },
    });
}

export async function listCronRuns(db: DrizzleClient): Promise<CronRunRecord[]> {
  return db.select().from(cronRuns);
}
