const express = require('express');
const router = express.Router();
const db = require('../db');
const bcrypt = require('bcryptjs');

// ----------------------------
// REGISTER
// ----------------------------
router.post('/register', (req, res) => {
  const { name, phone, password } = req.body;

  if (!name || !phone || !password) {
    return res.status(400).json({ message: 'All fields are required' });
  }

  // Check if phone/email already exists
  db.query('SELECT * FROM users WHERE phone=?', [phone], (err, results) => {
    if (err) return res.status(500).json({ error: err });

    if (results.length > 0) {
      return res.status(409).json({ message: 'Phone number already registered' });
    }

    // Hash password and insert new user
    const hashed = bcrypt.hashSync(password, 10);
    db.query(
      'INSERT INTO users (name, phone, password,role) VALUES (?, ?, ?,"user")',
      [name, phone, hashed],
      (err2) => {
        if (err2) return res.status(500).json({ error: err2 });
        res.json({ message: 'User registered successfully' });
      }
    );
  });
});

// ----------------------------
// LOGIN
// ----------------------------
router.post('/login', (req, res) => {
  const { phone, password } = req.body;

  if (!phone || !password) {
    return res.status(400).json({ message: 'Phone and password are required' });
  }

  db.query('SELECT * FROM users WHERE phone=?', [phone], (err, results) => {
    if (err) return res.status(500).json({ error: err });
    if (results.length === 0) return res.status(404).json({ message: 'User not found' });

    const user = results[0];
    if (!bcrypt.compareSync(password, user.password))
      return res.status(401).json({ message: 'Invalid password' });

    res.json({ user }); // removed token since you don't want it
  });
});

module.exports = router;
