const express = require('express');
const jwt=require('jsonwebtoken');
const router = express.Router();
const db=require('../config/database');

router.post('/register', async (req, res) => {
  const { email, password, role = 'user' } = req.body;

  const [existing] = await db.query('SELECT * FROM users WHERE email = ?', [email]);
  if (existing.length > 0) {
    return res.status(409).json({ message: 'User already registered' });
  }

  await db.query('INSERT INTO users (email, password, role) VALUES (?, ?, ?)', [email, password, role]);
  res.status(201).json({ message: 'User registered successfully' });
});

router.post('/login', async (req, res) => {
  const { email, password } = req.body;

  const [rows] = await db.query('SELECT * FROM users WHERE email = ? AND password = ?', [email, password]);

  if (rows.length === 0) {
    return res.status(401).json({ message: 'Invalid credentials' });
  }

  const user = rows[0];

  const token = jwt.sign(
    { userId: user.id, email: user.email, role: user.role },
    process.env.JWT_SECRET,
    { expiresIn: process.env.JWT_EXPIRES_IN }
  );

    const dashboardPath=user.role==='admin' ? 'api/dashhboard/admin' : 'api/dashboard/user';
    
  res.json({
    message: 'Login successful',
    token,
    role: user.role
  });
});

module.exports = router;