const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { PrismaClient } = require('@prisma/client');
const { JWT_SECRET, authenticateToken, isAdmin } = require('../middleware/auth');

const prisma = new PrismaClient();

// Register (Protected - Admin only or Open? Plan said Admin creates users)
// Let's allow open registration but default to USER role, or only Admin can create.
// Requirement: "administrador sea capaz de crear y borrar usuarios".
// So we will make register protected by isAdmin or just login.
// For initial setup we might need a seed or allow open registration for the first user.
// Let's implement a public login and a protected register for now.

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

    try {
        const user = await prisma.user.findUnique({ where: { username } });
        if (!user) return res.status(400).json({ error: 'User not found' });

        const validPassword = await bcrypt.compare(password, user.password);
        if (!validPassword) return res.status(400).json({ error: 'Invalid password' });

        const token = jwt.sign({ id: user.id, username: user.username, role: user.role }, JWT_SECRET, { expiresIn: '1h' });
        res.json({ token, role: user.role, username: user.username });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

// Admin: Create User
router.post('/register', authenticateToken, isAdmin, async (req, res) => {
    const { username, password, role } = req.body;

    try {
        const hashedPassword = await bcrypt.hash(password, 10);
        const user = await prisma.user.create({
            data: {
                username,
                password: hashedPassword,
                role: role || 'USER'
            }
        });
        res.json({ message: 'User created', userId: user.id });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

// Admin: Delete User
router.delete('/:id', authenticateToken, isAdmin, async (req, res) => {
    const { id } = req.params;
    try {
        await prisma.user.delete({ where: { id: parseInt(id) } });
        res.json({ message: 'User deleted' });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

// Admin: List Users
router.get('/', authenticateToken, isAdmin, async (req, res) => {
    try {
        const users = await prisma.user.findMany({
            select: { id: true, username: true, role: true } // Don't return passwords
        });
        res.json(users);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});


module.exports = router;
