import { parseDateOnly } from "@batch-cooking/date-tools";
import { HttpError } from "@batch-cooking/error-tools";
import { wrapAsyncHandler } from "@batch-cooking/express-tools";
import { ErrorCode, getCookingSessionSchema } from "@batch-cooking/shared";
import { Router } from "express";
import { type AuthLocals, requireAuth } from "../../middlewares/require-auth.js";
import { getCookingPlanForDate } from "./cooking-session.service.js";

/** Router mounted at `/cooking-session` in app.ts. */
export const cookingSessionRouter = Router();

/**
 * Returns the authenticated user's household's optimized cooking plan for
 * the week covering `?date=` (`YYYY-MM-DD`) — every recipe planned that
 * week reorganized into ordered phases (see {@link getCookingPlanForDate}).
 * Always `200`, never `null` — no household or nothing planned that week
 * both come back as a normal `OptimizedCookingPlanView` with empty
 * `recipes`/`phases`. Same request contract as `GET /shopping-list`.
 */
cookingSessionRouter.get(
  "/",
  requireAuth,
  wrapAsyncHandler<unknown, AuthLocals>(async (req, res) => {
    const input = getCookingSessionSchema.parse(req.query);
    const date = parseDateOnly(input.date);
    if (date === null) {
      throw new HttpError(
        400,
        ErrorCode.VALIDATION_ERROR,
        `Not a real calendar date: ${input.date}`,
      );
    }

    const plan = await getCookingPlanForDate(res.locals.userProfile.houseId, date);
    res.status(200).json(plan);
  }),
);
