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

const SYSTEM_USER_ID = '00000000-0000-0000-0000-000000000000';

(async () => {
  const pool = new Pool({ connectionString: process.env.LOCAL_DB_URL });
  const client = await pool.connect();
  try {
    const summary = await client.query(`
      SELECT
        (SELECT COUNT(*)::int FROM profiles) AS profiles,
        (SELECT COUNT(*)::int FROM auth.users) AS auth_users,
        (SELECT COUNT(*)::int FROM auth.users WHERE password_hash IS NULL OR password_hash = '') AS auth_without_password_hash,
        (SELECT COUNT(*)::int FROM works) AS works_total,
        (SELECT COUNT(*)::int FROM works WHERE status = 'completed' AND is_public = true) AS public_works,
        (SELECT COUNT(*)::int FROM works w LEFT JOIN profiles p ON p.id = w.user_id WHERE w.status = 'completed' AND w.is_public = true AND p.id IS NULL) AS public_missing_profile,
        (SELECT COUNT(*)::int FROM works WHERE status = 'completed' AND is_public = true AND user_id = $1) AS public_system_user
    `, [SYSTEM_USER_ID]);

    const byUser = await client.query(`
      SELECT
        COALESCE(p.email, '[missing-profile]') AS email,
        COALESCE(p.nickname, '') AS nickname,
        w.user_id,
        COUNT(*)::int AS works,
        COUNT(*) FILTER (WHERE w.is_public = true AND w.status = 'completed')::int AS public_works,
        COUNT(*) FILTER (WHERE w.is_public = false AND w.status = 'completed')::int AS history_works
      FROM works w
      LEFT JOIN profiles p ON p.id = w.user_id
      WHERE w.status = 'completed'
      GROUP BY w.user_id, p.email, p.nickname
      ORDER BY works DESC
    `);

    const noHashUsers = await client.query(`
      SELECT p.email, p.nickname, p.role, p.created_at
      FROM auth.users u
      JOIN profiles p ON p.id = u.id
      WHERE u.password_hash IS NULL OR u.password_hash = ''
      ORDER BY p.created_at DESC
      LIMIT 20
    `);

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