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

const SECRET_KEY = 'SMARTPARK_DIRECT_SECRET_KEY_12345';

// [CREATE] - Register a new user
router.post('/register', async (req, res) => {
    const { username, password } = req.body;
    try {
        const hashedPassword = await bcrypt.hash(password, 10);
        await db.query('INSERT INTO user (username, password_hash) VALUES (?, ?)', [username, hashedPassword]);
        res.status(201).json({ message: "User registered successfully" });
    } catch (err) { res.status(500).json({ error: err.message }); }
});

// [READ ALL] - Fetch all system users
router.get('/users', async (req, res) => {
    try {
        const [users] = await db.query('SELECT userid, username, last_login FROM user');
        res.json(users);
    } catch (err) { res.status(500).json({ error: err.message }); }
});

// [UPDATE] - Update a user's password
router.put('/users/:id', async (req, res) => {
    const { id } = req.params;
    const { newPassword } = req.body;
    try {
        const hashedPassword = await bcrypt.hash(newPassword, 10);
        await db.query('UPDATE user SET password_hash = ? WHERE userid = ?', [hashedPassword, id]);
        res.json({ message: "Password updated successfully" });
    } catch (err) { res.status(500).json({ error: err.message }); }
});

// [DELETE] - Remove a user account
router.delete('/users/:id', async (req, res) => {
    const { id } = req.params;
    try {
        await db.query('DELETE FROM user WHERE userid = ?', [id]);
        res.json({ message: "User account deleted successfully" });
    } catch (err) { res.status(500).json({ error: err.message }); }
});

// LOGIN SYSTEM CONTROLLER
router.post('/login', async (req, res) => {
    const { username, password } = req.body;
    try {
        const [users] = await db.query('SELECT * FROM user WHERE username = ?', [username]);
        if (users.length === 0) return res.status(404).json({ error: "User not found" });

        const isMatch = await bcrypt.compare(password, users[0].password_hash);
        if (!isMatch) return res.status(401).json({ error: "Invalid credentials" });

        const token = jwt.sign({ id: users[0].userid }, SECRET_KEY, { expiresIn: '1h' });
        res.json({ token, username: users[0].username });
    } catch (err) { res.status(500).json({ error: err.message }); }
});

module.exports = router;