import express from 'express';
import { apiKeysDb } from '../database/db.js';

const router = express.Router();

// Regenerate API key — deactivate old ones, create new
router.post('/regenerate', async (req, res) => {
  try {
    const userId = req.user.id;
    await apiKeysDb.deactivateAll(userId);
    const newKey = await apiKeysDb.createApiKey(userId, 'default');
    res.json({
      success: true,
      apiKey: newKey.api_key,
      keyName: newKey.keyName,
      message: 'API key regenerated. Store it safely — it won\'t be shown again.',
    });
  } catch (error) {
    console.error('Key regeneration error:', error);
    res.status(500).json({ error: 'Failed to regenerate API key' });
  }
});

// List all API keys
router.get('/', async (req, res) => {
  try {
    const keys = await apiKeysDb.getApiKeys(req.user.id);
    res.json({ keys });
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch API keys' });
  }
});

export default router;
