/**
 * Loop: claim gateway_outbox rows and invoke rail adapter `send`.
 * Run: npx ts-node -r tsconfig-paths/register src/workers/run-gateway-outbox-worker.ts
 * Env: DATABASE_URL, optional GATEWAY_OUTBOX_BATCH_SIZE, GATEWAY_OUTBOX_MAX_ATTEMPTS
 */

import { PrismaClient } from '@prisma/client';
import { GatewayOutboxWorker } from './gateway-outbox.worker';
import { logger } from '@/infrastructure/monitoring/logger';

const prisma = new PrismaClient();

async function main() {
	logger.info('GatewayOutboxWorker: starting');
	const worker = new GatewayOutboxWorker(prisma);

	let shutdown = false;
	const onShutdown = () => {
		shutdown = true;
		logger.info('GatewayOutboxWorker: shutdown signal');
	};
	process.on('SIGINT', onShutdown);
	process.on('SIGTERM', onShutdown);

	while (!shutdown) {
		const n = await worker.runOnce();
		if (n === 0) {
			await new Promise((r) => setTimeout(r, 500));
		}
	}

	await prisma.$disconnect();
	process.exit(0);
}

main().catch(async (e) => {
	logger.error('GatewayOutboxWorker: fatal', { error: e instanceof Error ? e.message : e });
	await prisma.$disconnect().catch(() => undefined);
	process.exit(1);
});
