import { query } from '../db/connection.js';

export async function listTags() {
  const { rows } = await query(`
    SELECT t.*, COUNT(rt.recipe_id) as recipe_count
    FROM tags t
    LEFT JOIN recipe_tags rt ON t.id = rt.tag_id
    GROUP BY t.id
    ORDER BY t.name
  `);
  return rows;
}

export async function getRecipesByTag(tagName: string) {
  const { rows: tagRows } = await query('SELECT * FROM tags WHERE name = $1 OR slug = $1', [tagName]);
  if (tagRows.length === 0) return null;
  const tag = tagRows[0];
  const { rows: recipes } = await query(`
    SELECT r.*, c.name as category_name
    FROM recipes r
    JOIN recipe_tags rt ON r.id = rt.recipe_id
    LEFT JOIN categories c ON r.category_id = c.id
    WHERE rt.tag_id = $1
    ORDER BY r.created_at DESC
  `, [tag.id]);
  return { tag, recipes };
}
