const { Pool } = require('pg');
require('dotenv').config({ path: '.env.local' });

(async () => {
  const pool = new Pool({ connectionString: process.env.LOCAL_DB_URL });
  const client = await pool.connect();
  try {
    const summary = await client.query(`
      SELECT
        COUNT(*)::int AS total,
        COUNT(*) FILTER (WHERE w.user_id IS NULL)::int AS null_user_id,
        COUNT(*) FILTER (WHERE p.id IS NULL)::int AS missing_profile,
        COUNT(*) FILTER (WHERE p.id IS NOT NULL)::int AS linked_profile
      FROM works w
      LEFT JOIN profiles p ON p.id = w.user_id
      WHERE w.is_public = true AND w.status = 'completed'
    `);

    const samples = await client.query(`
      SELECT
        w.id,
        w.user_id,
        w.title,
        LEFT(COALESCE(w.prompt, ''), 80) AS prompt_preview,
        w.params,
        w.created_at
      FROM works w
      LEFT JOIN profiles p ON p.id = w.user_id
      WHERE w.is_public = true AND w.status = 'completed' AND p.id IS NULL
      ORDER BY w.created_at DESC
      LIMIT 20
    `);

    const profileSamples = await client.query(`
      SELECT id, email, nickname, role, created_at
      FROM profiles
      ORDER BY created_at DESC
      LIMIT 20
    `);

    console.log(JSON.stringify({
      summary: summary.rows[0],
      missingSamples: samples.rows,
      profileSamples: profileSamples.rows,
    }, null, 2));
  } finally {
    client.release();
    await pool.end();
  }
})().catch((error) => {
  console.error(error);
  process.exit(1);
});
