const express = require('express');
const bodyParser = require('body-parser');
const twilio = require('twilio');

const app = express();
const port = 3000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Replace these values with your Twilio account SID and Auth Token
const accountSid = 'AC6a78dcc9798834795059baf4885738e5';
const authToken = 'e5e9c9023316f8ce8c05b99ffeaff38a';
const client = twilio(accountSid, authToken);

// Generate a random 6-digit OTP
function generateOTP() {
  return Math.floor(100000 + Math.random() * 900000);
}

// Store generated OTPs (in-memory, for simplicity)
const otpMap = new Map();

app.post('/send-otp', (req, res) => {
  const { phoneNumber } = req.body;

  if (!phoneNumber) {
    return res.status(400).json({ error: 'Phone number is required' });
  }

  const otp = generateOTP();
  otpMap.set(phoneNumber, otp);

  // Use Twilio to send the OTP via SMS
  client.messages
    .create({
      body: `Your OTP is: ${otp}`,
      from: '+917284941088',
      to: phoneNumber,
    })
    .then(() => {
      res.json({ success: true, message: 'OTP sent successfully' });
    })
    .catch((error) => {
      console.error(error);
      res.status(500).json({ error: 'Failed to send OTP' });
    });
});

app.post('/verify-otp', (req, res) => {
  const { phoneNumber, enteredOTP } = req.body;

  if (!phoneNumber || !enteredOTP) {
    return res.status(400).json({ error: 'Phone number and OTP are required' });
  }

  const storedOTP = otpMap.get(phoneNumber);

  if (storedOTP && storedOTP === parseInt(enteredOTP, 10)) {
    res.json({ success: true, message: 'OTP verified successfully' });
  } else {
    res.status(401).json({ error: 'Invalid OTP' });
  }
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});