const { sendSms, sendOtp, verifyOtp } = require('../model/smsModel');

/**
 * POST /api/sms/send
 * body: {
 *   mobile: string,
 *   var1: string,
 *   orderId: string
 * }
 */
exports.sendSmsC = async (req, res) => {
  const { mobile, var1 ,var2 ,templateName , senderId } = req.body;

  if (!mobile || !var1) {
    return res.status(400).json({ error: 'mobile and var1 are required' });
  }

  try {
    const data = await sendSms(mobile, var1 ,var2, templateName , senderId);
    
    if (data.Status === 'Success') {
      return res.json({ success: true, data });
    } else {
      return res.status(502).json({
        success: false,
        message: 'SMS API error',
        details: data,
      });
    }
  } catch (err) {
    console.error('SMS request failed:', err.response?.data || err.message);
    return res.status(502).json({
      success: false,
      error: err.response?.data || err.message,
    });
  }
};


exports.sendOtpC = async(req , res) =>{
  try {
    const { mobile, templateName } = req.body;
    console.log(req.body);

    console.log( mobile, templateName);

    if (!mobile || !templateName) {
      return res.status(400).json({
        status: 'error',
        message: 'mobile number and template are required'
      });
    }

    const result = await sendOtp(mobile, templateName);

    // You may want to inspect result.Status or result.Details
    if (result.Status === 'Success') {
      return res.json({
        status: 'ok',
        message: 'OTP sent',
        data: result.Details
      });
    } else {
      return res.status(422).json({
        status: 'failed',
        message: result.Details || 'Verification failed'
      });
    }
  } catch (err) {
    console.error('Error in sendingOtp:', err);
    
  }
};

exports.verifyOtpC = async(req , res) =>{
  try {
    const { mobile, otp } = req.body;

    if (!mobile || !otp) {
      return res.status(400).json({
        status: 'error',
        message: 'enter otp'
      });
    }

    const result = await verifyOtp(mobile, otp);

    // You may want to inspect result.Status or result.Details
    if (result.Status === 'Success') {
      return res.json({
        status: 'ok',
        message: 'OTP verified',
        data: result.Details
      });
    } else {
      return res.status(422).json({
        status: 'failed',
        message: result.Details || 'Verification failed'
      });
    }
  } catch (err) {
    console.error('Error in handleVerifyOtp:', err);
    
  }
}
