const fs = require('fs');
const path = require('path');
const { CocTeam } = require('../../models');
const { deleteFile } = require('../../helpers');
const { errorHandler } = require('../../util');

exports.createCocTeam = async (req, res, next) => {
	try {
		let data = { ...req.body };

		const image = req?.files?.cocImg?.[0];
		if (image) {
			data.image = image.filename;
		}

		const cocTeam = await CocTeam.create(data);
		return res.status(201).json({
			success: true,
			data: cocTeam,
		});
	} catch (error) {
		next(error);
	}
};

exports.updateCocTeam = async (req, res, next) => {
	try {
		let data = { ...req.body };
		const cocTeam = await CocTeam.findByPk(req.params.id);
		if (!cocTeam) return errorHandler('Not found', 404);

		const newImage = req?.files?.cocImg?.[0];
		if (newImage) {
			if (cocTeam.image) {
				deleteFile(cocTeam.image, 'coc-uploads');
			}
			data.image = newImage.filename;
		}

		await CocTeam.update(data, { where: { id: req.params.id } });
		const updatedTeam = await CocTeam.findByPk(req.params.id);
		return res.json({
			success: true,
			data: {
				...updatedTeam.get({ plain: true }),
				image: updatedTeam.image ? path.join('coc-uploads', updatedTeam.image) : null,
			},
			message: 'Coc Team updated successfully',
		});
	} catch (error) {
		next(error);
	}
};

exports.deleteCocTeam = async (req, res, next) => {
	try {
		const cocTeam = await CocTeam.findByPk(req.params.id);
		if (!cocTeam) return errorHandler('Not found', 404);

		if (cocTeam.image) {
			deleteFile(cocTeam.image, 'coc-uploads');
		}

		await CocTeam.destroy({ where: { id: req.params.id } });
		return res.status(200).json({
			success: true,
			message: 'Coc Team deleted successfully',
		});
	} catch (error) {
		next(error);
	}
};
