import { FastifyInstance } from 'fastify';
import { optionalAuthMiddleware, authMiddleware } from '../middleware/auth.js';
import * as svc from '../services/recipe.service.js';

export async function recipeRoutes(app: FastifyInstance) {
  app.get('/api/recipes/random', async (request, reply) => {
    const { categories } = request.query as { categories?: string };
    const categorySlugs = categories ? categories.split(',') : undefined;
    const recipe = await svc.getRandomRecipe(categorySlugs);
    if (!recipe) return reply.status(404).send({ error: 'No recipes found' });
    return recipe;
  });

  app.get('/api/recipes/search', async (request) => {
    const { q } = request.query as { q?: string };
    if (!q) return { data: [], total: 0 };
    const results = await svc.searchRecipes(q);
    return { data: results, total: results.length };
  });

  app.get('/api/recipes', { preHandler: [optionalAuthMiddleware] }, async (request) => {
    const query = request.query as any;
    const userId = request.user?.id;
    
    return await svc.listRecipes({
      page: query.page ? Number(query.page) : undefined,
      limit: query.limit ? Number(query.limit) : undefined,
      category_id: query.category_id,
      category_slug: query.category,
      favorite: query.favorite !== undefined ? query.favorite === 'true' : undefined,
      difficulty: query.difficulty,
      maxTime: query.maxTime ? Number(query.maxTime) : undefined,
      userId: userId,
    });
  });

  app.get('/api/recipes/:slug', async (request, reply) => {
    const { slug } = request.params as { slug: string };
    const recipe = await svc.getRecipeBySlug(slug);
    if (!recipe) return reply.status(404).send({ error: 'Not found' });
    return recipe;
  });

  app.post('/api/recipes', async (request, reply) => {
    const body = request.body as svc.CreateRecipeInput;
    if (!body.title) return reply.status(400).send({ error: 'title required' });
    const recipe = await svc.createRecipe(body);
    return reply.status(201).send(recipe);
  });

  app.put('/api/recipes/:id', async (request, reply) => {
    const { id } = request.params as { id: string };
    const recipe = await svc.updateRecipe(id, request.body as any);
    if (!recipe) return reply.status(404).send({ error: 'Not found' });
    return recipe;
  });

  app.delete('/api/recipes/:id', async (request, reply) => {
    const { id } = request.params as { id: string };
    const ok = await svc.deleteRecipe(id);
    if (!ok) return reply.status(404).send({ error: 'Not found' });
    return { ok: true };
  });

  app.patch('/api/recipes/:id/favorite', { preHandler: [optionalAuthMiddleware] }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const userId = request.user?.id;
    
    const result = await svc.toggleFavorite(id, userId);
    if (!result) return reply.status(404).send({ error: 'Not found' });
    return result;
  });
}
