const dbConnect = require('../configs/dbConnection.js');
const { sendOtp, verifyOtp } = require('../../smsapi/model/smsModel');
const { verifyCaptcha } = require('../utils/verifyCaptcha.js');
const bcrypt = require('bcryptjs');

// ── Step 1: password verify → OTP send ──
exports.login = async (req, res) => {
  try {
    const { mobile, password } = req.body;
    console.log('[SignIn Step1] mobile:', mobile);
    if (!mobile || !password) {
      return res.status(400).json({ error: 'All fields are mandatory' });
    }
    const [rows] = await dbConnect.query(
      `SELECT uid, uname, upass, umob, umail FROM alogin WHERE umob = ?`,
      [mobile]
    );
    if (rows.length === 0) {
      return res.status(401).json({ error: 'You are not registered' });
    }
    const user = rows[0];
    const match = await bcrypt.compare(password, user.upass);
    if (!match) {
      return res.status(400).json({ error: 'Incorrect password' });
    }
    const formattedMobile = '+91' + String(mobile).replace(/\D/g, '').replace(/^0|^91/, '');
    console.log('[SignIn Step1] sending OTP to:', formattedMobile);
    const sendSmsResponse = await sendOtp(formattedMobile, 'BOBROSOTP');
    console.log('[SignIn Step1] sendOtp response:', sendSmsResponse);
    if (!sendSmsResponse) {
      return res.status(500).json({ error: 'Failed to send OTP' });
    }
    return res.status(200).json({
      message: 'OTP sent successfully',
      otpSent: true,
    });
  } catch (error) {
    console.error('Error in signin step1:', error.message);
    return res.status(500).json({ error: 'Failed to sign in' });
  }
};

// ── Step 2: OTP verify → user data + services return ──
exports.verifyLoginOtp = async (req, res) => {
  try {
    const { mobile, otp } = req.body;
    if (!mobile || !otp) {
      return res.status(400).json({ error: 'mobile and otp are required' });
    }

    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 uid, uname, umob, umail FROM alogin WHERE umob = ?`,
      [mobile]
    );
    if (rows.length === 0) {
      return res.status(404).json({ error: 'User not found' });
    }

    const user = rows[0];
    console.log('[SignIn Step2] OTP verified, user:', user.uid);

    // ── agent_services — row లేకపోతే default insert ──
    // const [svcCheck] = await dbConnect.query(
    //   `SELECT uid FROM agent_services WHERE uid = ?`,
    //   [user.uid]
    // );

    // if (svcCheck.length === 0) {
    //   // First login — default row create (అన్నీ 0)
    //   await dbConnect.query(
    //     `INSERT INTO agent_services (uid) VALUES (?)`,
    //     [user.uid]
    //   );
    //   console.log('[SignIn Step2] agent_services default row created for uid:', user.uid);
    // }

    // Services fetch
    const [svcRows] = await dbConnect.query(
      `SELECT bus, flights, hotels, holidays, cabs, bill_payments, it_services
       FROM agent_services WHERE uid = ?`,
      [user.uid]
    );
    const services = svcRows[0] || {};
    console.log('[SignIn Step2] services:', services);

    return res.status(200).json({
      message: 'Login successful',
      user: {
        uid:      user.uid,
        uname:    user.uname,
        umob:     user.umob,
        umail:    user.umail,
        services, // { bus: 0, flights: 0, ... }
      },
    });

  } catch (error) {
    console.error('Error in signin step2:', error.message);
    return res.status(500).json({ error: 'Failed to verify OTP' });
  }
};