const express = require('express');
const jwt = require('jsonwebtoken');
const { JWT_SECRET, authenticateToken } = require('../middleware/auth');
const { findAdminByKey } = require('../config/load-admins');

const router = express.Router();

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

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

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

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

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

router.post('/verify', authenticateToken, (req, res) => {
  if (!req.user.name) {
    return res.status(403).json({ error: 'Token missing admin identity, please re-login' });
  }

  res.json({
    valid: true,
    user: req.user
  });
});

module.exports = router;
