const db = require("../db/db");
const { generateSIS } = require("../utils/idGenerator");
const { sanitizeString } = require("../utils/validators");

/**
 * Start a new session (Go Online)
 * Expects: deviceRegistrationId, location {latitude, longitude}, connectivityType, wifiBssid (optional)
 */
async function startSession(req, res, next) {
  try {
    const { deviceRegistrationId, location, connectivityType, wifiBssid } = req.body;

    // Validate required fields
    if (!deviceRegistrationId) {
      const err = new Error("Missing device registration ID");
      err.statusCode = 400;
      throw err;
    }

    if (!location || typeof location.latitude !== "number" || typeof location.longitude !== "number") {
      const err = new Error("Invalid or missing location");
      err.statusCode = 400;
      throw err;
    }

    const validConnTypes = ["wifi", "cellular", "mobile", "unknown"];
    const connType = (connectivityType || "unknown").toLowerCase();
    if (!validConnTypes.includes(connType)) {
      const err = new Error("Invalid connectivity type");
      err.statusCode = 400;
      throw err;
    }

    // Verify device registration exists
    const deviceCheck = await db.query(
      "SELECT device_registration_id FROM device_registrations WHERE device_registration_id = $1",
      [deviceRegistrationId]
    );

    if (deviceCheck.rows.length === 0) {
      const err = new Error("Device not registered");
      err.statusCode = 404;
      throw err;
    }

    // Generate session ID
    const sis = generateSIS();

    // Insert session
    await db.query(
      `INSERT INTO sessions 
       (session_id, device_registration_id, latitude, longitude, connectivity_type, wifi_bssid)
       VALUES ($1, $2, $3, $4, $5, $6)`,
      [
        sis,
        deviceRegistrationId,
        location.latitude,
        location.longitude,
        connType,
        connType === "wifi" ? sanitizeString(wifiBssid, 50) : null,
      ]
    );

    return res.json({
      success: true,
      sessionId: sis,
    });
  } catch (e) {
    next(e);
  }
}

module.exports = { startSession };
