import { Router } from 'express';
import crypto from 'crypto';
import db from '../db.js';
import { generateSurgeConfig } from '../services/generator.js';

const router = Router();

// GET /api/config/surge-token - get current surge token
router.get('/surge-token', (_req, res) => {
  const row = db.prepare("SELECT value FROM config WHERE key = 'surge_token'").get() as any;
  res.json({ token: row?.value || null });
});

// POST /api/config/surge-token - regenerate surge token
router.post('/surge-token', (_req, res) => {
  const token = crypto.randomUUID();
  db.prepare("INSERT OR REPLACE INTO config (key, value) VALUES ('surge_token', ?)").run(token);
  res.json({ token });
});

// GET /api/config/preview - preview generated config
router.get('/preview', (req, res) => {
  const host = req.headers.host || 'localhost:3456';
  const protocol = req.secure ? 'https' : 'http';
  const row = db.prepare("SELECT value FROM config WHERE key = 'surge_token'").get() as any;
  const token = row?.value || '';
  const hostUrl = `${protocol}://${host}/surge/${token}`;

  const config = generateSurgeConfig(hostUrl);
  res.json({ config });
});

export default router;
