import { execute, queryOne } from '@/lib/db/connection';

export type StripeEventClaim = 'process' | 'skip';

export async function claimStripeEvent(
  eventId: string,
  eventType: string
): Promise<StripeEventClaim> {
  const existing = await queryOne<{ processed_at: Date | null }>(
    `SELECT processed_at FROM stripe_events WHERE id = $1`,
    [eventId]
  );

  if (existing?.processed_at) return 'skip';

  if (!existing) {
    await execute(`INSERT INTO stripe_events (id, type) VALUES ($1, $2)`, [eventId, eventType]);
    return 'process';
  }

  return 'process';
}

export async function markStripeEventProcessed(eventId: string): Promise<void> {
  await execute(`UPDATE stripe_events SET processed_at = NOW() WHERE id = $1`, [eventId]);
}
