/**
 * Cron: Personal Deal Timeout - runs every 5 minutes.
 *
 * FDS §6.6: If vendor does not respond within the response window,
 * the personal deal request expires and the user is notified.
 *
 * Calls expireOverdueRequests(deps: PersonalDealDeps) from the personal-deal workflow.
 * PersonalDealDeps requires { db, push }. We create a real PushClient for this cron.
 */

import { createDbService } from '@/server/services/db.js';
import { withSentry } from '@/server/observability/with-sentry';
import { createPushClient } from '../push/send.js';
import { env as runtimeEnv } from '@/server/env.js';
import { buildServices } from '@/server/services/bundle.js';
import type { CronEnv } from './deal-expiry.js';

export const runPersonalDealTimeout = withSentry(
  async function runPersonalDealTimeout(env: CronEnv): Promise<void> {
    const db = env.db ?? createDbService({ DATABASE_URL: env.DATABASE_URL });

    try {
      const { expireOverdueRequests } = await import('../workflows/personal-deal.js');

      // Build a push client only if VAPID keys are present (graceful degradation)
      const push =
        env.VAPID_PUBLIC_KEY && env.VAPID_PRIVATE_KEY && env.VAPID_SUBJECT
          ? createPushClient(db, {
              VAPID_PUBLIC_KEY: env.VAPID_PUBLIC_KEY,
              VAPID_PRIVATE_KEY: env.VAPID_PRIVATE_KEY,
              VAPID_SUBJECT: env.VAPID_SUBJECT,
              DATABASE_URL: env.DATABASE_URL,
            })
          : {
              sendToUser: async () => undefined,
              sendToVendor: async () => undefined,
            };

      const services = await buildServices(runtimeEnv);
      await expireOverdueRequests({ db, push, doClient: services.doClient });
    } catch (err) {
      // Workflow module may not yet exist - no-op fallback
      if (!(err instanceof Error && err.message.includes('Cannot find module'))) {
        throw err;
      }
      // When the workflow module is ready (Agent 2C), this will be wired up.
    }
  },
  { name: 'cron.personal-deal-timeout', kind: 'cron' },
);
