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

class AuthService {
    async register(userData) {
        const { username, email, password, role } = userData;
        const password_hash = await bcrypt.hash(password, 10);

        const [result] = await db.execute(
            'INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)',
            [username, email, password_hash, role || 'STAFF']
        );

        return { id: result.insertId, username, email, role };
    }

    async login(username, password) {
        const [users] = await db.execute('SELECT * FROM users WHERE username = ? AND is_active = 1', [username]);
        const user = users[0];

        if (!user || !(await bcrypt.compare(password, user.password_hash))) {
            throw new Error('Invalid credentials');
        }

        const token = jwt.sign(
            { id: user.id, username: user.username, role: user.role },
            process.env.JWT_SECRET,
            { expiresIn: '24h' }
        );

        return {
            token,
            user: {
                id: user.id,
                username: user.username,
                email: user.email,
                role: user.role
            }
        };
    }

    async getAllUsers() {
        const [rows] = await db.execute('SELECT id, username, email, role, is_active, last_login, created_at FROM users');
        return rows;
    }

    async updateUser(id, userData) {
        const { username, email, role, password } = userData;
        let query = 'UPDATE users SET username = ?, email = ?, role = ?';
        let params = [username, email, role || 'STAFF'];

        if (password) {
            const password_hash = await bcrypt.hash(password, 10);
            query += ', password_hash = ?';
            params.push(password_hash);
        }

        query += ' WHERE id = ?';
        params.push(id);

        await db.execute(query, params);
        return { id, username, email, role };
    }

    async deleteUser(id) {
        await db.execute('DELETE FROM users WHERE id = ?', [id]);
        return { id, deleted: true };
    }
}

module.exports = new AuthService();
