import query from '../server-utils/query.js';
import { declareHandler } from '../server-utils/routesHandler.js';
import { UserRole } from '../types/serverTypes.js';

export const getQuestions = declareHandler({
  func: async (req, res) => {
    if (req.user.role !== UserRole.Admin) return res.status(403).send({ error: 'Not authorized' });

    const questions = await query(`SELECT * FROM faq_questions ORDER BY faq_questions.id;`, []);
    res.send(questions.rows);
  },
});

export const getAnswers = declareHandler({
  func: async (req, res) => {
    if (req.user.role !== UserRole.Admin) return res.status(403).send({ error: 'Not authorized' });

    const answers = await query(
      `
        SELECT fa.*, COUNT(fq.id) as question_count, STRING_AGG(CAST(fq.id AS TEXT), ', ') as question_ids
        FROM faq_answers fa
        LEFT JOIN faq_questions fq ON fq.answer_id = fa.id
        GROUP BY fa.id;
        ORDER BY fa.id;
      `,
      []
    );
    res.send(answers.rows);
  },
});

export const getQuestion = declareHandler({
  func: async (req, res) => {
    if (req.user.role !== UserRole.Admin) return res.status(403).send({ error: 'Not authorized' });

    const { id } = req.params;
    const question = await query(
      `
        SELECT fq.*, fa.answer 
        FROM faq_questions fq LEFT JOIN faq_answers fa ON fq.answer_id = fa.id 
        WHERE fq.id = $1
      `,
      [id]
    );
    res.send(question.rows[0]);
  },
});

export const getAnswer = declareHandler({
  func: async (req, res) => {
    if (req.user.role !== UserRole.Admin) return res.status(403).send({ error: 'Not authorized' });

    const { id } = req.params;
    const answer = await query(
      `
        SELECT fa.*, 
        json_agg(json_build_object('id', fq.id, 'question', fq.question)) as questions
        FROM faq_answers fa
        LEFT JOIN faq_questions fq ON fa.id = fq.answer_id
        WHERE fa.id = $1
        GROUP BY fa.id;
      `,
      [id]
    );
    res.send(answer.rows[0]);
  },
});

export const updateQuestion = declareHandler({
  func: async (req, res) => {
    if (req.user.role !== UserRole.Admin) return res.status(403).send({ error: 'Not authorized' });

    const { id } = req.params;
    const { question } = req.body;
    const updatedQuestion = await query(
      `
        UPDATE faq_questions SET question = $1 WHERE id = $2 RETURNING *;
      `,
      [question, id]
    );
    res.send(updatedQuestion.rows[0]);
  },
});

export const updateAnswer = declareHandler({
  func: async (req, res) => {
    if (req.user.role !== UserRole.Admin) return res.status(403).send({ error: 'Not authorized' });

    const { id } = req.params;
    const { answer } = req.body;
    const updatedAnswer = await query(
      `
        UPDATE faq_answers SET answer = $1 WHERE id = $2 RETURNING *;
      `,
      [answer, id]
    );
    res.send(updatedAnswer.rows[0]);
  },
});

export const createQuestion = declareHandler({
  func: async (req, res) => {
    if (req.user.role !== UserRole.Admin) return res.status(403).send({ error: 'Not authorized' });

    const { question, answer, answerId } = req.body;
    let answerIdToUse = answerId;
    if (answer) {
      const newAnswer = await query(`INSERT INTO faq_answers (answer) VALUES ($1) RETURNING *;`, [answer]);
      answerIdToUse = newAnswer.rows[0].id;
    }
    const newQuestion = await query(`INSERT INTO faq_questions (question, answer_id) VALUES ($1, $2) RETURNING *;`, [
      question,
      answerIdToUse,
    ]);
    res.send(newQuestion.rows[0]);
  },
});
