const express = require('express');
const router = express.Router();
const db = require('../db/init');

// Check if system is configured
router.get('/status', (req, res) => {
  db.get('SELECT COUNT(*) as count FROM config', [], (err, row) => {
    if (err) return res.status(500).json({ error: err.message });
    res.json({ configured: row.count > 0 });
  });
});

// Initial setup of credentials
router.post('/setup', (req, res) => {
  const { adminUser, adminPass, boothUser, boothPass } = req.body;

  db.serialize(() => {
    db.run('BEGIN TRANSACTION');
    db.run('DELETE FROM config'); // Clear any existing just in case
    
    const stmt = db.prepare('INSERT INTO config (role, username, password) VALUES (?, ?, ?)');
    stmt.run('admin', adminUser, adminPass);
    stmt.run('booth', boothUser, boothPass);
    stmt.finalize();

    db.run('COMMIT', (err) => {
      if (err) {
        db.run('ROLLBACK');
        return res.status(500).json({ error: 'Setup failed' });
      }
      res.json({ success: true, message: 'System configured successfully' });
    });
  });
});

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

  db.get('SELECT role FROM config WHERE username = ? AND password = ?', [username, password], (err, row) => {
    if (err) return res.status(500).json({ error: err.message });
    
    if (row) {
      return res.json({ role: row.role, token: `temp-token-${row.role}-${Date.now()}` });
    }

    res.status(401).json({ message: 'Invalid credentials' });
  });
});

module.exports = router;
