import fp from 'fastify-plugin';
import { ForbiddenError } from '../common/errors.js';

export default fp(
  async (fastify) => {
    fastify.addHook('preHandler', async (request) => {
      // Skip household check for public routes or routes that explicitly opt out
      const routeConfig = request.routeOptions.config as unknown as
        | Record<string, unknown>
        | undefined;
      if (routeConfig?.['public'] === true || routeConfig?.['skipHousehold'] === true) {
        return;
      }

      // householdId must be present in the route URL params (e.g. /households/:householdId/...)
      const params = request.params as Record<string, string> | undefined;
      const householdId = params?.['householdId'];
      if (!householdId) {
        return; // route has no household context — no scoping needed
      }

      // Validate user belongs to this household
      if (!request.user?.householdIds?.includes(householdId)) {
        throw new ForbiddenError('You do not belong to this household');
      }

      request.householdId = householdId;
    });
  },
  { name: 'household-plugin', dependencies: ['auth-plugin'] },
);
