import { Router } from 'express';
import pool from '../db.js';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { v4 as uuidv4 } from 'uuid';
const router = Router();
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-this';
// Login Route
router.post('/login', async (req, res) => {
    const { username, password } = req.body;
    try {
        const [rows] = await pool.query('SELECT * FROM users WHERE username = ?', [username]);
        const user = rows[0];
        if (!user) {
            return res.status(401).json({ error: 'Invalid credentials' });
        }
        const validPassword = await bcrypt.compare(password, user.password_hash);
        if (!validPassword) {
            return res.status(401).json({ error: 'Invalid credentials' });
        }
        const token = jwt.sign({ id: user.id, username: user.username, role: user.role }, JWT_SECRET, { expiresIn: '24h' });
        res.json({ token, user: { id: user.id, username: user.username, role: user.role } });
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
});
// Seed Initial Admin (For initial setup only)
router.post('/seed', async (req, res) => {
    try {
        const [rows] = await pool.query('SELECT * FROM users WHERE username = ?', ['admin']);
        if (rows.length > 0) {
            return res.status(400).json({ message: 'Admin user already exists' });
        }
        const hashedPassword = await bcrypt.hash('admin123', 10);
        const id = uuidv4();
        await pool.query('INSERT INTO users (id, username, password_hash) VALUES (?, ?, ?)', [id, 'admin', hashedPassword]);
        res.status(201).json({ message: 'Admin user created' });
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Failed to seed user' });
    }
});
export default router;
//# sourceMappingURL=auth.js.map