import { FastifyInstance } from 'fastify';
import * as recipeSvc from '../services/recipe.service.js';
import * as imageSvc from '../services/image.service.js';

export async function botRoutes(app: FastifyInstance) {
  const BOT_TOKEN = process.env.BOT_API_TOKEN;

  app.addHook('onRequest', async (request, reply) => {
    if (!BOT_TOKEN) return reply.status(503).send({ error: 'Bot API not configured' });
    const auth = request.headers.authorization;
    if (!auth || auth !== `Bearer ${BOT_TOKEN}`) {
      return reply.status(401).send({ error: 'Unauthorized' });
    }
  });

  app.get('/api/bot/recipes', async (request) => {
    const query = request.query as any;
    return await recipeSvc.listRecipes({
      page: query.page ? Number(query.page) : undefined,
      limit: query.limit ? Number(query.limit) : undefined,
    });
  });

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

  app.post('/api/bot/recipes/:id/image-url', async (request, reply) => {
    const { id } = request.params as { id: string };
    const { url } = request.body as { url: string };
    if (!url) return reply.status(400).send({ error: 'url required' });
    try {
      const result = await imageSvc.downloadAndSaveImage(id, url);
      if (!result) return reply.status(404).send({ error: 'Recipe not found' });
      return result;
    } catch (e: any) {
      return reply.status(400).send({ error: e.message });
    }
  });
}
