import express from 'express';
import { readFileSync, existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const router = express.Router();
const questionsPath = join(__dirname, '../data/questions.json');

// Helper функция для чтения вопросов
const getQuestions = () => {
  if (!existsSync(questionsPath)) {
    return { categories: [] };
  }
  const data = readFileSync(questionsPath, 'utf-8');
  return JSON.parse(data);
};

// GET все категории и вопросы
router.get('/', (req, res) => {
  try {
    const questions = getQuestions();
    res.json(questions);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

export default router;
