import { parseDateOnly } from "@batch-cooking/date-tools";
import { HttpError } from "@batch-cooking/error-tools";
import { wrapAsyncHandler } from "@batch-cooking/express-tools";
import { ErrorCode, getShoppingListSchema } from "@batch-cooking/shared";
import { Router } from "express";
import { analytics } from "../../lib/analytics.service.js";
import { type AuthLocals, requireAuth } from "../../middlewares/require-auth.js";
import { getShoppingListForDate } from "./shopping-list.service.js";

/** Router mounted at `/shopping-list` in app.ts. */
export const shoppingListRouter = Router();

/**
 * Returns the authenticated user's household's shopping list for the week
 * covering `?date=` (`YYYY-MM-DD`) — every ingredient line of every recipe
 * planned that week, summed (see {@link getShoppingListForDate}). Always
 * `200`, never `null` — no household or nothing planned that week both
 * come back as a normal `ShoppingListView` with an empty `items` array.
 */
shoppingListRouter.get(
  "/",
  requireAuth,
  wrapAsyncHandler<unknown, AuthLocals>(async (req, res) => {
    const input = getShoppingListSchema.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 shoppingList = await getShoppingListForDate(res.locals.userProfile.houseId, date);
    analytics.recordEvent("shopping_list.viewed", { actorId: res.locals.userProfile.id });
    res.status(200).json(shoppingList);
  }),
);
