import { optima } from "$lib";
import { json, error } from "@sveltejs/kit";
import type { RequestHandler } from "./$types";

/** GET /calendar/events?start=<ISO>&end=<ISO> — fetch schedule entries for the authenticated user */
export const GET: RequestHandler = async ({ url, locals }) => {
  const accessToken = locals.session?.accessToken;
  if (!accessToken) throw error(401, "Unauthorized");

  const startStr = url.searchParams.get("start");
  const endStr = url.searchParams.get("end");

  if (!startStr || !endStr) throw error(400, "start and end query params are required");

  const start = new Date(startStr);
  const end = new Date(endStr);

  if (isNaN(start.getTime()) || isNaN(end.getTime())) {
    throw error(400, "Invalid date format for start or end");
  }

  try {
    const entries = await optima.schedule.fetchMe(accessToken, start, end);
    return json({ data: entries });
  } catch (err: unknown) {
    console.error("Failed to fetch schedule entries:", err);
    const status =
      err && typeof err === "object" && "status" in err
        ? (err as { status: number }).status
        : 500;
    throw error(status, "Failed to fetch schedule entries");
  }
};
