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

const base = 'http://127.0.0.1:5000';
const email = `codex-delete-${Date.now()}@example.com`;

(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 pool = new Pool({ connectionString: process.env.LOCAL_DB_URL });
  const client = await pool.connect();
  let tempId = null;
  try {
    const created = await client.query(
      `INSERT INTO profiles (email, nickname, role, membership_tier, credits_balance, daily_quota_limit, is_active)
       VALUES ($1, 'DeleteVerify', 'user', 'free', 0, 5, true)
       RETURNING id`,
      [email],
    );
    tempId = created.rows[0].id;
    await client.query(
      `INSERT INTO works (user_id, type, prompt, result_url, is_public, status)
       VALUES ($1, 'text2img', 'delete verify', '/api/local-storage/non-existent.png', true, 'completed')`,
      [tempId],
    );
  } finally {
    client.release();
    await pool.end();
  }

  const deleteAdmin = await fetch(`${base}/api/admin/users`, {
    method: 'DELETE',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    body: JSON.stringify({ userId: adminId }),
  });
  const deleteAdminBody = await deleteAdmin.text();

  const deleteTemp = await fetch(`${base}/api/admin/users`, {
    method: 'DELETE',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    body: JSON.stringify({ userId: tempId }),
  });
  const deleteTempBody = await deleteTemp.text();

  const checkPool = new Pool({ connectionString: process.env.LOCAL_DB_URL });
  const checkClient = await checkPool.connect();
  try {
    const remain = await checkClient.query(
      `SELECT
        EXISTS(SELECT 1 FROM profiles WHERE id = $1) AS profile_exists,
        EXISTS(SELECT 1 FROM works WHERE user_id = $1) AS works_exist`,
      [tempId],
    );
    console.log(JSON.stringify({
      deleteAdmin: { status: deleteAdmin.status, body: deleteAdminBody },
      deleteTemp: { status: deleteTemp.status, body: deleteTempBody },
      remaining: remain.rows[0],
    }, null, 2));
  } finally {
    checkClient.release();
    await checkPool.end();
  }
})().catch(async (error) => {
  console.error(error);
  process.exit(1);
});
