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');

// Login Step 1
exports.loginAdmin = async (req, res) => {
  try {
    const { mobile, password } = req.body;

    const [rows] = await dbConnect.query(
      `SELECT *
       FROM admin_users
       WHERE dmob = ?`,
      [mobile]
    );

    if (rows.length === 0) {
      return res.status(401).json({
        error: 'Admin not found'
      });
    }

    const admin = rows[0];

    const match = await bcrypt.compare(
      password,
      admin.dpass
    );

    if (!match) {
      return res.status(401).json({
        error: 'Incorrect password'
      });
    }

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

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

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

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

// Login Step 2
exports.verifyLoginOtp = async (req, res) => {
  try {
    const { mobile, 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 [rows] = await dbConnect.query(
      `SELECT duser_accountId,
              dname,
              dmob,
              dmail,
              did,
              dflag
       FROM admin_users
       WHERE dmob = ?`,
      [mobile]
    );

    res.status(200).json({
      msg: 'Login successful',
      admin: rows[0]
    });

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