import { pool } from '../db.js';
import { config } from '../config.js';
import { processOverduePlatformInvoices } from '../../../api/src/features/platform-admin/service.js';

interface PlatformDunningWorkerResult {
  processed: number;
  markedOverdue: number;
  reminderCreated: number;
  skippedReminder: number;
}

export async function processPlatformDunningBatch(limit = config.platformDunningBatchSize): Promise<PlatformDunningWorkerResult> {
  const client = await pool.connect();
  try {
    await client.query('begin');
    const result = await processOverduePlatformInvoices(client, {
      channel: 'internal',
      limit,
      workerId: config.platformDunningWorkerId,
    });
    await client.query('commit');
    return {
      processed: Number(result.processed || 0),
      markedOverdue: Number(result.markedOverdue || 0),
      reminderCreated: Number(result.reminderCreated || 0),
      skippedReminder: Number(result.skippedReminder || 0),
    };
  } catch (error) {
    await client.query('rollback').catch(() => {});
    throw error;
  } finally {
    client.release();
  }
}
