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

export async function shoppingRoutes(app: FastifyInstance) {
  app.get('/api/shopping', { preHandler: [optionalAuthMiddleware] }, async (request) => {
    const { scope } = request.query as { scope?: 'personal' | 'household' };
    const userId = request.user?.id;
    return await svc.listItems(userId, scope || 'personal');
  });

  app.post('/api/shopping/from-recipe/:id', { preHandler: [optionalAuthMiddleware] }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const { scope } = request.query as { scope?: 'personal' | 'household' };
    const userId = request.user?.id;
    try {
      const items = await svc.addFromRecipe(id, userId, scope || 'personal');
      if (!items) return reply.status(404).send({ error: 'Recipe not found' });
      return reply.status(201).send({ added: items.length });
    } catch (error: any) {
      if (error.message === 'USER_NOT_IN_HOUSEHOLD') {
        return reply.status(400).send({ error: 'You are not a member of any household' });
      }
      throw error;
    }
  });

  app.post('/api/shopping', { preHandler: [optionalAuthMiddleware] }, async (request, reply) => {
    const { name, amount, unit } = request.body as { name: string; amount?: number; unit?: string };
    const { scope } = request.query as { scope?: 'personal' | 'household' };
    const userId = request.user?.id;
    if (!name) return reply.status(400).send({ error: 'name required' });
    try {
      const item = await svc.addItem(name, amount, unit, userId, scope || 'personal');
      return reply.status(201).send(item);
    } catch (error: any) {
      if (error.message === 'USER_NOT_IN_HOUSEHOLD') {
        return reply.status(400).send({ error: 'You are not a member of any household' });
      }
      throw error;
    }
  });

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

  app.delete('/api/shopping/all', { preHandler: [optionalAuthMiddleware] }, async (request) => {
    const { scope } = request.query as { scope?: 'personal' | 'household' };
    const userId = request.user?.id;
    const count = await svc.deleteAll(userId, scope || 'personal');
    return { ok: true, deleted: count };
  });

  app.delete('/api/shopping/checked', { preHandler: [optionalAuthMiddleware] }, async (request) => {
    const { scope } = request.query as { scope?: 'personal' | 'household' };
    const userId = request.user?.id;
    const count = await svc.deleteChecked(userId, scope || 'personal');
    return { ok: true, deleted: count };
  });

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