export { COOKIE_NAME, ONE_YEAR_MS } from "@shared/const";

// Generate login URL at runtime.
// If VITE_OAUTH_PORTAL_URL is configured, use Manus OAuth flow.
// Otherwise (production), redirect to our own email/password login page.
export const getLoginUrl = (returnPath?: string) => {
  const oauthPortalUrl = import.meta.env.VITE_OAUTH_PORTAL_URL;
  const base = import.meta.env.BASE_URL ?? "/";

  // No OAuth portal configured — use local login page
  if (!oauthPortalUrl) {
    const qs = returnPath ? `?returnTo=${encodeURIComponent(returnPath)}` : "";
    return `${base}login${qs}`;
  }

  // OAuth flow (Manus / external SSO)
  const appId = import.meta.env.VITE_APP_ID;
  const redirectUri = `${window.location.origin}${base}api/oauth/callback`;
  const statePayload = returnPath
    ? JSON.stringify({ redirectUri, returnPath })
    : redirectUri;
  const state = btoa(statePayload);

  const url = new URL(`${oauthPortalUrl}/app-auth`);
  url.searchParams.set("appId", appId);
  url.searchParams.set("redirectUri", redirectUri);
  url.searchParams.set("state", state);
  url.searchParams.set("type", "signIn");

  return url.toString();
};
