const express = require('express');
const bcrypt = require('bcryptjs'); // 'bcryptjs' nk'uko iri muri package.json yawe
const jwt = require('jsonwebtoken');
const router = express.Router();
const db = require('../config/db');

// 1. REGISTER USER (RECEPTIONIST / ADMIN)
router.post('/register', async (req, res) =>  {
    const { username, password, role } = req.body;

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

    try {
        const [existing] = await db.query('SELECT * FROM users WHERE username = ?', [username]);
        if (existing.length > 0) {
            return res.status(400).json({ message: 'Username is already taken' });
        }

        // KOSORA HANO: Gukoresha genSaltSync na hashSync ziboneka muri bcryptjs
        const salt = bcrypt.genSaltSync(10);
        const hashedPassword = bcrypt.hashSync(password, salt);

        await db.query(
            'INSERT INTO users (username, password, role) VALUES (?, ?, ?)',
            [username, hashedPassword, role || 'Receptionist']
        );

        return res.status(201).json({ message: 'User registered successfully!' });
    } catch (err) {
        console.error(err);
        return res.status(500).json({ message: 'Internal server error' });
    }
});

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

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

    try {
        const [users] = await db.query('SELECT * FROM users WHERE username = ?', [username]);
        if (users.length === 0) {
            return res.status(401).json({ message: 'Invalid username or password' });
        }

      const user = users[0]; // Fata umukoresha wa mbere uri muri array neza neza!
const isMatch = bcrypt.compareSync(password, user.password);

        if (!isMatch) {
            return res.status(401).json({ message: 'Invalid username or password' });
        }

        const token = jwt.sign(
            { id: user.UserId, username: user.username, role: user.role },
            process.env.JWT_SECRET || 'fallback_secret',
            { expiresIn: '1d' }
        );

        return res.status(200).json({
            message: 'Login successful',
            token,
            user: { id: user.UserId, username: user.username, role: user.role }
        });
    } catch (err) {
        console.error(err);
        return res.status(500).json({ message: 'Internal server error' });
    }
});

module.exports = router;
