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

export async function noteRoutes(app: FastifyInstance) {
  app.get('/api/recipes/:id/notes', { preHandler: [optionalAuthMiddleware] }, async (request) => {
    const { id } = request.params as { id: string };
    const userId = request.user?.id;
    return await svc.listNotes(id, userId);
  });

  app.post('/api/recipes/:id/notes', { preHandler: [optionalAuthMiddleware] }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const { content } = request.body as { content: string };
    const userId = request.user?.id;
    if (!content) return reply.status(400).send({ error: 'content required' });
    const note = await svc.createNote(id, content, userId);
    if (!note) return reply.status(404).send({ error: 'Recipe not found' });
    return reply.status(201).send(note);
  });

  app.put('/api/notes/:id', { preHandler: [optionalAuthMiddleware] }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const { content } = request.body as { content: string };
    const userId = request.user?.id;
    if (!content) return reply.status(400).send({ error: 'content required' });
    const note = await svc.updateNote(id, content, userId);
    if (!note) return reply.status(404).send({ error: 'Not found' });
    return note;
  });

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