require('dotenv').config();
const { Pool } = require('pg');

if (process.env.CONFIRM_STAGING_RESET !== 'RESET_JNM_STAGING') {
  console.error('Reset refused. Set CONFIRM_STAGING_RESET=RESET_JNM_STAGING for this one command.');
  process.exit(1);
}
if (String(process.env.NODE_ENV || '').toLowerCase() === 'production' && process.env.ALLOW_PRODUCTION_RESET !== 'YES') {
  console.error('Reset refused in production. This command is for an empty private staging database.');
  process.exit(1);
}

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

(async () => {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    // notifications.student_id is the one legacy non-cascading student link.
    await client.query('UPDATE notifications SET student_id=NULL WHERE student_id IS NOT NULL');
    const students = await client.query('DELETE FROM students RETURNING id');

    // Curriculum is retained. Nullable creator/reviewer links are detached before
    // deleting the test parent accounts.
    await client.query('UPDATE courses SET created_by=NULL WHERE created_by IS NOT NULL');
    await client.query('UPDATE assignments SET created_by=NULL WHERE created_by IS NOT NULL');
    await client.query('UPDATE grades SET graded_by=NULL WHERE graded_by IS NOT NULL');
    await client.query('UPDATE retakes SET approved_by=NULL WHERE approved_by IS NOT NULL');
    await client.query('UPDATE comments SET user_id=NULL WHERE user_id IS NOT NULL');
    await client.query('UPDATE daily_logs SET logged_by=NULL WHERE logged_by IS NOT NULL');
    await client.query('UPDATE attendance SET recorded_by=NULL WHERE recorded_by IS NOT NULL');
    const users = await client.query('DELETE FROM users RETURNING id');
    await client.query("SELECT setval(pg_get_serial_sequence('students','id'), 1, false)");
    await client.query("SELECT setval(pg_get_serial_sequence('users','id'), 1, false)");
    await client.query('COMMIT');
    console.log(JSON.stringify({ reset:'complete', removed_students:students.rowCount, removed_users:users.rowCount, curriculum_preserved:true }, null, 2));
  } catch (error) {
    await client.query('ROLLBACK');
    console.error('Staging reset failed and was rolled back:', error.message);
    process.exitCode = 1;
  } finally {
    client.release();
    await pool.end();
  }
})();
