const { Op } = require('sequelize');
const { Faqs } = require('../../models');
const { errorHandler } = require('../../util');
const { formatCase } = require('../../util/formatter');

exports.createFaq = async (req, res, next) => {
	try {
		const { question, answer, order } = req.body;

		const faq = await Faqs.create({
			question,
			answer,
			order,
		});

		return res.status(201).json({
			success: true,
			message: 'FAQ created successfully',
			data: formatCase(faq.get({ plain: true })),
		});
	} catch (error) {
		next(error);
	}
};

exports.updateFaq = async (req, res, next) => {
	try {
		const { question, answer, order, id } = req.body;

		const faq = await Faqs.findByPk(id);
		if (!faq) {
			return errorHandler('FAQ not found', 404);
		}

		const updateData = {};
		if (question !== undefined) updateData.question = question;
		if (answer !== undefined) updateData.answer = answer;
		if (order !== undefined) updateData.order = order;

		await faq.update(updateData);

		return res.status(200).json({
			success: true,
			message: 'FAQ updated successfully',
			data: formatCase(faq.get({ plain: true })),
		});
	} catch (error) {
		next(error);
	}
};

exports.deleteFaq = async (req, res, next) => {
	try {
		const { id } = req.params;

		const faq = await Faqs.findByPk(id);
		if (!faq) {
			return errorHandler('FAQ not found', 404);
		}

		await faq.destroy();

		return res.status(200).json({
			success: true,
			message: 'FAQ deleted successfully',
		});
	} catch (error) {
		next(error);
	}
};
