import express from 'express';
import { Request, Response } from 'express';
import { pool } from '../config/db';
import { Question } from '../models/Question';
import { createLogger } from '../utils/logger';

const router = express.Router();
const logger = createLogger('questionRoutes');

// Get the creator of a specific lobby
router.get('/amount/:amount', async (req: Request, res: Response): Promise<void> => {
  const { amount } = req.params;
  try {
    const result = await pool.query<Question>(
      'SELECT id, question, answer FROM question ORDER BY RANDOM() LIMIT $1',
      [amount]
    );
    const randomQuestions = result.rows as Question[];

    logger.info(JSON.stringify(randomQuestions));
    if (result.rows.length === 0) {
      res.status(404).json({ error: 'No questions found in the database' });
      return;
    }

    res.json(randomQuestions);
    return;
  } catch (err) {
    logger.error('Error fetching random question', err);
    res.status(500).json({ error: 'Internal Server Error' });
    return;
  }
});

// GET all unique tags from questions
router.get('/tags', async (req: Request, res: Response): Promise<void> => {
  try {
    logger.info('Fetching all unique tags');
    
    const result = await pool.query(`
      SELECT DISTINCT tag 
      FROM question 
      WHERE tag IS NOT NULL AND tag != ''
      ORDER BY tag
    `);
    
    const tags = result.rows.map(row => row.tag);
    
    logger.info(`Found ${tags.length} unique tags`);
    res.json(tags);
  } catch (err) {
    logger.error('Error fetching tags:', err);
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

export default router;
