import { DiaryTag, DiaryDateTag } from '../models/index.js';

export const getTags = async (req, res) => {
    try {
        const tags = await DiaryTag.findAll();
        res.status(200).json(tags);
    } catch (error) {
        res.status(500).json({ error: 'Error fetching tags' });
    }
};

export const createTag = async (req, res) => {
    try {
        const { name } = req.body;
        if (!name) {
            return res.status(400).json({ error: 'Der Name des Tags ist erforderlich.' });
        }

        const [tag, created] = await DiaryTag.findOrCreate({ where: { name }, defaults: { name } });
        res.status(created ? 201 : 200).json(tag);
    } catch (error) {
        res.status(500).json({ error: 'Error creating tag' });
    }
};

export const deleteTag = async (req, res) => {
    try {
        const { tagId } = req.params;

        await DiaryDateTag.destroy({ where: { tagId } });
        const deleted = await DiaryTag.destroy({ where: { id: tagId } });

        if (!deleted) {
            return res.status(404).json({ error: 'Tag nicht gefunden' });
        }

        res.status(200).json({ message: 'Tag deleted' });
    } catch (error) {
        console.error('[deleteTag] - Error:', error);
        res.status(500).json({ error: 'Error deleting tag' });
    }
};
