import { createRoute } from "../../../modules/api-utils/createRoute";
import { schedules } from "../../../managers/schedules";
import { apiResponse } from "../../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../../middleware/authorization";
import GenericError from "../../../Errors/GenericError";

/* /v1/schedule/member/:memberId?start=<ISO>&end=<ISO> */
export default createRoute(
  "get",
  ["/member/:memberId"],
  async (c) => {
    const memberId = c.req.param("memberId");
    const startParam = c.req.query("start");
    const endParam = c.req.query("end");

    if (!memberId) {
      throw new GenericError({
        name: "BadRequest",
        message: "memberId path parameter is required.",
        status: 400,
      });
    }

    if (!startParam || !endParam) {
      throw new GenericError({
        name: "BadRequest",
        message: "Query params 'start' and 'end' are required (ISO 8601 date strings).",
        status: 400,
      });
    }

    const startDate = new Date(startParam);
    const endDate = new Date(endParam);

    if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
      throw new GenericError({
        name: "BadRequest",
        message: "Invalid date format. Use ISO 8601 (e.g. 2026-04-01T00:00:00Z).",
        status: 400,
      });
    }

    if (startDate >= endDate) {
      throw new GenericError({
        name: "BadRequest",
        message: "'start' must be before 'end'.",
        status: 400,
      });
    }

    const data = await schedules.fetchByMemberDateRange(memberId, startDate, endDate);

    const response = apiResponse.successful(
      "Schedule entries fetched successfully!",
      data.map((s) => s.toJson()),
    );

    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ permissions: ["schedule.fetch.many"] }),
);
