import express, { Router } from 'express';
import { ApiKeyService } from '../services/ApiKeyService';

const router: Router = express.Router();
const apiKeyService = new ApiKeyService();

/**
 * Bootstrap endpoint - creates the first master key
 * Only works when no keys exist in the database
 *
 * POST /api/bootstrap/initial-key
 */
router.post('/initial-key', async (_req, res): Promise<void> => {
  try {
    // Check if any keys already exist
    const hasKeys = await apiKeyService.hasAnyKeys();

    if (hasKeys) {
      console.warn(`[${new Date().toISOString()}] Bootstrap attempt when keys already exist`);
      res.status(403).json({
        error: 'Bootstrap not allowed',
        message: 'API keys already exist. Use /api/admin/keys to create new keys.',
      });
      return;
    }

    // Create first master key
    const { key, metadata } = await apiKeyService.createMasterKey('Initial Master Key');

    console.log(
      `[${new Date().toISOString()}] Initial master key created via bootstrap: ${metadata.id}`,
    );

    res.status(201).json({
      apiKey: key,
      type: metadata.keyType,
      name: metadata.name,
      expiresAt: metadata.expiresAt,
      message: 'IMPORTANT: Save this key securely. You will not see it again!',
    });
  } catch (error) {
    console.error(`[${new Date().toISOString()}] Bootstrap error:`, error);
    res.status(500).json({
      error: 'Bootstrap failed',
      message: 'Failed to create initial API key',
    });
  }
});

export default router;
