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

/* GET /v1/time-entry/time-entries?page=&rpp=&search= */
export default createRoute(
    "get",
    ["/time-entries"],
    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");

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

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

        const response = apiResponse.successful(
            "Time entries fetched successfully!",
            data.map((e) => e.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: ["time-entry.fetch.many"] }),
);
