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

const base = 'http://127.0.0.1:5000';

(async () => {
  const adminRes = await fetch(`${base}/api/profile?email=admin@example.com`);
  const adminData = await adminRes.json();
  const adminId = adminData.profile && adminData.profile.id;
  if (!adminId) throw new Error('admin profile not found');
  const token = `token-admin-${adminId}-${Date.now()}`;

  const statsRes = await fetch(`${base}/api/admin/stats`, {
    headers: { Authorization: `Bearer ${token}` },
  });
  const stats = await statsRes.json();

  const pool = new Pool({ connectionString: process.env.LOCAL_DB_URL });
  const client = await pool.connect();
  try {
    const db = await client.query(`
      SELECT
        (SELECT COUNT(*)::int FROM profiles WHERE COALESCE(role, 'user') NOT IN ('admin', 'enterprise_admin')) AS users_without_admin,
        (SELECT COUNT(*)::int FROM works WHERE is_public = true AND status = 'completed') AS public_works
    `);
    console.log(JSON.stringify({
      status: statsRes.status,
      stats,
      db: db.rows[0],
    }, null, 2));
  } finally {
    client.release();
    await pool.end();
  }
})().catch((error) => {
  console.error(error);
  process.exit(1);
});
