import { wrapAsyncHandler } from "@batch-cooking/express-tools";
import { updatePreferencesSchema } from "@batch-cooking/shared";
import { Router } from "express";
import { type AuthLocals, requireAuth } from "../../middlewares/require-auth.js";
import { getPreferences, updatePreferences } from "./preferences.service.js";

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

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

preferencesRouter.patch(
  "/",
  requireAuth,
  wrapAsyncHandler<unknown, AuthLocals>(async (req, res) => {
    const input = updatePreferencesSchema.parse(req.body);
    const preferences = await updatePreferences(res.locals.userProfile.id, input.theme);
    res.status(200).json(preferences);
  }),
);
