const config = require('./config');
const db = require('./db');
const app = require('./app');

async function migrate() {
  const [cols] = await db.query(
    `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
     WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'users' AND COLUMN_NAME = 'mobile_verified_at'`,
    [config.db.database],
  );
  if (!cols[0]) {
    await db.query('ALTER TABLE users ADD COLUMN mobile_verified_at DATETIME NULL AFTER password_hash');
  }
  await db.query(
    `UPDATE users u
     JOIN sessions s ON s.user_id = u.id
     SET u.mobile_verified_at = NOW()
     WHERE u.mobile_verified_at IS NULL`,
  );
}

function startServer() {
  // cPanel / Phusion Passenger must get listen() during startup, not after DB work.
  const passenger = typeof PhusionPassenger !== 'undefined';
  if (passenger) {
    PhusionPassenger.configure({ autoInstall: false });
    app.listen('passenger');
    console.log('GPS tracker API running under Passenger');
    return;
  }

  app.listen(config.port, '0.0.0.0', () => {
    console.log(`GPS tracker API running at http://127.0.0.1:${config.port}`);
  });
}

startServer();

migrate().catch((err) => {
  console.error('Database migrate failed (API is still up — check DB env vars)', err);
});
