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

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

app.use(cors());
app.use(bodyParser.json());

let users = [];

app.post('/signup', (req, res) => {
  const { username, email, password } = req.body;
  if (!username || !email || !password) {
    return res.status(400).send('All fields are required');
  }

  const existingUser = users.find(u => u.email === email);
  if (existingUser) {
    return res.status(400).send('User already exists');
  }

  users.push({ username, email, password });
  res.status(201).send({ message: 'User registered successfully' });
});

app.post('/login', (req, res) => {
  const { email, password } = req.body;
  const user = users.find(u => u.email === email && u.password === password);

  if (user) {
    res.status(200).send({ message: 'Login successful' });
  } else {
    res.status(401).send('Invalid credentials');
  }
});

app.post('/forgot-password', (req, res) => {
  const { email } = req.body;
  const user = users.find(u => u.email === email);

  if (user) {
    console.log(`Password reset instructions sent to ${email}`);
    res.status(200).send({ message: 'Password reset instructions have been sent to your email.' });
  } else {
    res.status(404).send('User not found');
  }
});

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