const db = require("../db/db");
const { generateDID } = require("../utils/idGenerator");
const { validateMobile, validateName, sanitizeString } = require("../utils/validators");

async function registerDevice(req, res, next) {
  try {
    const { name, mobile, deviceInfo, appVersion } = req.body;

    // Validate and sanitize inputs
    const sanitizedName = validateName(name);
    const sanitizedMobile = validateMobile(mobile);
    const sanitizedAppVersion = sanitizeString(appVersion, 30);

    if (!sanitizedName) {
      const err = new Error("Invalid or missing name");
      err.statusCode = 400;
      throw err;
    }

    if (!sanitizedMobile) {
      const err = new Error("Invalid or missing mobile number (10-15 digits required)");
      err.statusCode = 400;
      throw err;
    }

    if (!deviceInfo || typeof deviceInfo !== "object") {
      const err = new Error("Missing device info");
      err.statusCode = 400;
      throw err;
    }

    if (!sanitizedAppVersion) {
      const err = new Error("Missing app version");
      err.statusCode = 400;
      throw err;
    }

    const did = generateDID();

    await db.query(
      `INSERT INTO device_registrations
      (device_registration_id, name, mobile, device_model, manufacturer, os, os_version, device_id, app_version)
      VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
      [
        did,
        sanitizedName,
        sanitizedMobile,
        sanitizeString(deviceInfo.deviceModel, 100) || null,
        sanitizeString(deviceInfo.manufacturer, 100) || null,
        sanitizeString(deviceInfo.os, 50) || null,
        sanitizeString(deviceInfo.osVersion, 50) || null,
        sanitizeString(deviceInfo.deviceId, 100) || null,
        sanitizedAppVersion,
      ]
    );

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

module.exports = { registerDevice };
