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";

/* /v1/schedule/schedules */
export default createRoute(
  "get",
  ["/schedules"],
  async (c) => {
    const page = new Number(c.req.query("page") ?? 1) as number;
    const rpp = new Number(c.req.query("rpp") ?? 30) as number;
    const search = c.req.query("search") as string;

    const data = search
      ? await schedules.search(search, page, rpp)
      : await schedules.fetchPages(page, rpp);

    const totalRecords = search
      ? (await schedules.search(search, 1, 999999)).length
      : await schedules.count();

    const response = apiResponse.successful(
      "Schedules Fetched Successfully!",
      data.map((s) => s.toJson()),
      {
        pagination: {
          previousPage: page == 1 ? null : page - 1,
          currentPage: page,
          nextPage: page >= totalRecords / rpp ? null : page + 1,
          totalPages: Math.ceil(totalRecords / rpp),
          totalRecords,
          listedRecords: rpp,
        },
      },
    );

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