'use strict';

const { fetchTags } = require('../tags');

async function fetchTagsApi(req, res) {
    const tagId = typeof req.params.tagId === 'number' ? req.params.tagId : undefined; // null will literally include NULL results
    const tagSlug = typeof req.params.tagId === 'string' ? req.params.tagId : undefined;

    if (tagId || tagSlug) {
        const tags = await fetchTags({
            id: tagId,
            slug: tagSlug,
        }, null, req.query.limit);

        if (tags.length > 0) {
            res.send(tags[0]);
            return;
        }

        res.status(404).send();
        return;
    }

    const query = {};
    const groupsQuery = {};

    if (req.query.priority) query.priority = req.query.priority.split(',');
    if (req.query.slug) query.slug = req.query.slug.split(',');
    if (req.query.group) {
        groupsQuery.slug = req.query.group.split(',');
    }

    const tags = await fetchTags(query, groupsQuery, req.query.limit);

    res.send(tags);
}

module.exports = {
    fetchTags: fetchTagsApi,
};
