const express = require('express');
const jwt = require('jsonwebtoken');
const { JWT_SECRET, authenticateToken } = require('../middleware/auth');

const router = express.Router();

if (!process.env.ADMIN_KEY) {
  throw new Error('ADMIN_KEY environment variable is required');
}
const ADMIN_KEY = process.env.ADMIN_KEY;

// Login with admin key
router.post('/login', (req, res) => {
  const { key } = req.body;

  if (!key) {
    return res.status(400).json({ error: 'Admin key is required' });
  }

  if (key !== ADMIN_KEY) {
    return res.status(401).json({ error: 'Invalid admin key' });
  }

  // Generate JWT token
  const token = jwt.sign(
    { role: 'admin', timestamp: Date.now() },
    JWT_SECRET,
    { expiresIn: '24h' }
  );

  res.json({ 
    token, 
    message: 'Authentication successful',
    expiresIn: '24h'
  });
});

// Verify token validity
router.post('/verify', authenticateToken, (req, res) => {
  res.json({ 
    valid: true, 
    user: req.user 
  });
});

module.exports = router;

