const { Client } = require('pg');
require('dotenv').config({ path: '/root/miaojingAI/.env.local' });

(async () => {
  const client = new Client({ connectionString: process.env.LOCAL_DB_URL });
  await client.connect();
  try {
    await client.query('BEGIN');
    const admin = await client.query(
      `SELECT id FROM profiles WHERE role = 'admin' ORDER BY created_at ASC LIMIT 1`,
    );
    if (!admin.rows[0]?.id) {
      throw new Error('No admin profile found');
    }
    const result = await client.query(
      `UPDATE generation_jobs
       SET user_id = $1
       WHERE user_id IS NULL
       RETURNING id`,
      [admin.rows[0].id],
    );
    await client.query('COMMIT');

    const summary = await client.query(
      `SELECT status,
              count(*)::int AS count,
              count(*) FILTER (WHERE user_id IS NULL)::int AS null_user_count
       FROM generation_jobs
       GROUP BY status
       ORDER BY status`,
    );
    console.log(JSON.stringify({
      backfilled: result.rowCount,
      adminUserId: admin.rows[0].id,
      summary: summary.rows,
    }, null, 2));
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  } finally {
    await client.end();
  }
})().catch((error) => {
  console.error(error);
  process.exit(1);
});
