const dbConnect = require('../../busapi/configs/dbConnection');
const { sendOtp, verifyOtp } = require('../../smsapi/model/smsModel');
const { encrypt, hashMobile, hashEmail } = require('./busapi/controllers/cryptoUtil.js');
const bcrypt = require('bcryptjs');

// Register Step 1
exports.registerAdmin = async (req, res) => {
  try {
    const { name, mobile, email, password } = req.body;

    if (!name || !mobile || !email || !password) {
      return res.status(400).json({
        error: 'name, mobile, email, password are required'
      });
    }

    const [existing] = await dbConnect.query(
      `SELECT dmob, dmail
       FROM admin_users
       WHERE dmob = ? OR dmail = ?`,
      [mobile, email]
    );

    if (existing.length > 0) {
      return res.status(409).json({
        error: 'Mobile or email already registered'
      });
    }

    const formattedMobile =
      '+91' + String(mobile).replace(/\D/g, '').replace(/^0|^91/, '');

    const sendSmsResponse = await sendOtp(
      formattedMobile,
      'BOBROSOTP'
    );

    return res.status(200).json({
      msg: 'OTP sent successfully',
      sendSmsResponse
    });

  } catch (error) {
    return res.status(500).json({
      error: error.message
    });
  }
};

// Register Step 2
exports.verifyRegisterOtp = async (req, res) => {
  try {
    const { name, mobile, email, password, otp } = req.body;

    const isOtpValid = await verifyOtp(mobile, otp);

    if (!isOtpValid || isOtpValid.Details === 'OTP Mismatch') {
      return res.status(400).json({
        error: 'OTP verification failed'
      });
    }

    const hashedPassword = await bcrypt.hash(password, 10);

    const did = 'ADM' + Date.now();

    const [result] = await dbConnect.query(
      `INSERT INTO admin_users
      (duser, dpass, dname, did, dflag, dmail, dmob)
      VALUES (?, ?, ?, ?, 'Active', ?, ?)`,
      [mobile, hashedPassword, name, did, email, mobile]
    );

    res.status(201).json({
      msg: 'Admin registered successfully',
      adminId: result.insertId
    });

  } catch (error) {
    res.status(500).json({
      error: error.message
    });
  }
};