import { wrapAsyncHandler } from "@batch-cooking/express-tools";
import {
  updateAllergiesSchema,
  updateDietSchema,
  updateDislikedIngredientsSchema,
} from "@batch-cooking/shared";
import { Router } from "express";
import { type AuthLocals, requireAuth } from "../../middlewares/require-auth.js";
import {
  getAllergyIds,
  getDislikedIngredientIds,
  updateAllergies,
  updateDiet,
  updateDislikedIngredients,
} from "./profile.service.js";

/** Router mounted at `/profile` in app.ts. Every route requires a session — this is the authenticated user's own profile. */
export const profileRouter = Router();

/** The regime step of the profile journey (signup wizard and the `/foyer` settings page both call this). */
profileRouter.patch(
  "/diet",
  requireAuth,
  wrapAsyncHandler<unknown, AuthLocals>(async (req, res) => {
    const input = updateDietSchema.parse(req.body);
    const profile = await updateDiet(res.locals.userProfile.id, input.dietId);
    res.status(200).json(profile);
  }),
);

profileRouter.get(
  "/allergies",
  requireAuth,
  wrapAsyncHandler<unknown, AuthLocals>(async (_req, res) => {
    const allergyIds = await getAllergyIds(res.locals.userProfile.id);
    res.status(200).json(allergyIds);
  }),
);

/** The allergen/intolerance step of the profile journey — same callers as PATCH /diet above. */
profileRouter.patch(
  "/allergies",
  requireAuth,
  wrapAsyncHandler<unknown, AuthLocals>(async (req, res) => {
    const input = updateAllergiesSchema.parse(req.body);
    const allergyIds = await updateAllergies(res.locals.userProfile.id, input.allergyIds);
    res.status(200).json(allergyIds);
  }),
);

profileRouter.get(
  "/disliked-ingredients",
  requireAuth,
  wrapAsyncHandler<unknown, AuthLocals>(async (_req, res) => {
    const ids = await getDislikedIngredientIds(res.locals.userProfile.id);
    res.status(200).json(ids);
  }),
);

/** Personal taste preference — distinct from `/allergies`, which is medical. Managed from `/parametres/preferences` (see `PreferencesPage.tsx`). */
profileRouter.patch(
  "/disliked-ingredients",
  requireAuth,
  wrapAsyncHandler<unknown, AuthLocals>(async (req, res) => {
    const input = updateDislikedIngredientsSchema.parse(req.body);
    const ids = await updateDislikedIngredients(
      res.locals.userProfile.id,
      input.dislikedIngredientIds,
    );
    res.status(200).json(ids);
  }),
);
