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";
import GenericError from "../../../Errors/GenericError";

/* GET /v1/time-entry/@me?start=<ISO>&end=<ISO> */
export default createRoute(
    "get",
    ["/@me"],
    async (c) => {
        const user = c.get("user");

        if (!user?.cwIdentifier) {
            throw new GenericError({
                name: "BadRequest",
                message:
                    "Your account is not linked to a ConnectWise member. Cannot fetch time entries.",
                status: 400,
            });
        }

        const startParam = c.req.query("start");
        const endParam = c.req.query("end");

        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 timeEntries.fetchByDateRange(
            startDate,
            endDate,
            user.cwIdentifier,
        );

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

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