// Smoke test for /api/class-room. Uses a freshly-init'd dev DB. Run with:
//   cd server && node scripts/smoke-class-room.js

const http = require('http');
const jwt = require('jsonwebtoken');
const { spawn } = require('node:child_process');
const path = require('node:path');

const PORT = 3301;
const SECRET = 'dev-only-insecure-secret';

const child = spawn(process.execPath, [path.join(__dirname, '..', 'src', 'index.js')], {
  env: { ...process.env, PORT: String(PORT), JWT_SECRET: SECRET, NODE_ENV: 'development' },
  stdio: 'inherit',
});

function get(pathname, token) {
  return new Promise((resolve, reject) => {
    const req = http.request(
      { host: '127.0.0.1', port: PORT, path: pathname, method: 'GET',
        headers: token ? { Authorization: `Bearer ${token}` } : {} },
      (res) => {
        let data = '';
        res.on('data', (c) => (data += c));
        res.on('end', () => resolve({ status: res.statusCode, body: data }));
      }
    );
    req.on('error', reject);
    req.end();
  });
}

async function waitForServer(maxMs = 8000) {
  const start = Date.now();
  while (Date.now() - start < maxMs) {
    try {
      const r = await get('/api/sync/status');
      // sync status is admin-only; any response other than ECONNREFUSED is "up".
      if (r.status > 0) return;
    } catch (_e) {}
    await new Promise((r) => setTimeout(r, 250));
  }
  throw new Error('server did not start');
}

(async () => {
  try {
    await waitForServer();
    const adminToken = jwt.sign(
      { id: 1, email: 'admin@school.com', role: 'school_admin' },
      SECRET,
      { expiresIn: '7d' }
    );
    const studentToken = jwt.sign(
      { id: 99, email: 'student@school.com', role: 'student' },
      SECRET,
      { expiresIn: '7d' }
    );

    const adminRes = await get('/api/class-room', adminToken);
    console.log('ADMIN STATUS', adminRes.status);
    console.log('ADMIN BODY', adminRes.body.slice(0, 800));

    const studentRes = await get('/api/class-room', studentToken);
    console.log('STUDENT STATUS', studentRes.status, JSON.parse(studentRes.body).note);

    process.exitCode = 0;
  } catch (err) {
    console.error('ERR', err.message);
    process.exitCode = 1;
  } finally {
    child.kill('SIGTERM');
  }
})();
