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

/**
 * Token refresh endpoint.
 *
 * Forces a token refresh using the refresh token cookie regardless of whether
 * the server hook already refreshed. This handles cases where the API returns
 * a 401 for a token the hook considers still-valid (e.g. revocation, clock
 * skew). New tokens are written into cookies so the browser cookie jar is
 * always in sync with what the client receives.
 *
 * Client-side code that receives a 401 from a direct API call can:
 *   1. GET /api/auth/refresh  → receives the fresh accessToken
 *   2. Retry the original request with the new token
 */
export const GET: RequestHandler = async ({ locals, cookies }) => {
  const refreshToken = cookies.get("refreshToken") ?? null;

  if (!refreshToken) {
    return json({ error: "Not authenticated" }, { status: 401 });
  }

  try {
    const refreshed = await optima.user.refreshSession(refreshToken);
    const newAccessToken: string = refreshed.accessToken;
    const newRefreshToken: string = refreshed.refreshToken ?? refreshToken;

    // Update cookies so the browser has the latest tokens
    cookies.set("accessToken", newAccessToken, { path: "/" });
    cookies.set("refreshToken", newRefreshToken, { path: "/" });

    // Keep locals in sync for anything downstream in this request
    if (locals.session) {
      locals.session.accessToken = newAccessToken;
      locals.session.refreshToken = newRefreshToken;
    }

    return json({ accessToken: newAccessToken });
  } catch {
    return json({ error: "Session expired" }, { status: 401 });
  }
};
