import { getAuthState } from './saas/saas-api';
import { currentClientReturnPath } from './saas/auth-card';

export const COMPILE_AUTH_REQUIRED_EVENT = 'learnitive:compile-auth-required';

export type CompileAuthRequiredDetail = {
  returnTo: string;
};

export function requestCompileAuthentication(returnTo = currentClientReturnPath()): void {
  if (typeof window === 'undefined') return;
  window.dispatchEvent(
    new CustomEvent<CompileAuthRequiredDetail>(COMPILE_AUTH_REQUIRED_EVENT, {
      detail: { returnTo },
    }),
  );
}

export async function ensureCompileAuthentication(): Promise<boolean> {
  try {
    const auth = await getAuthState();
    if (auth.authenticated) return true;
    requestCompileAuthentication();
    return false;
  } catch {
    // Authentication remains enforced server-side. A transient auth-state lookup
    // failure should not mislabel a signed-in user as anonymous.
    return true;
  }
}
