export interface AuthUser {
  sub: string;
  email: string;
  name: string;
  preferredUsername: string | null;
  avatarUrl: string | null;
  groups: string[];
}

export interface AuthenticatedSession {
  authenticated: true;
  user: AuthUser;
  groups: string[];
  isSuperAdmin: boolean;
  logoutUrl: string;
}

export interface UnauthenticatedSession {
  authenticated: false;
  loginUrl: string;
}

export type AuthSession = AuthenticatedSession | UnauthenticatedSession;

export interface LauncherAuthApp {
  id: string;
  slug: string;
  title: string;
  description: string;
  url: string;
  openUrl: string;
  status: string;
  provider: string;
  requiredGroups: string[];
  matchedGroups: string[];
  hasAccess: boolean;
  accessReason: string;
  media?: {
    icon?: string | null;
    coverImage?: string | null;
    accentColor?: string | null;
  };
}

export async function fetchAuthSession(): Promise<AuthSession> {
  const response = await fetch("/api/me", { cache: "no-store" });

  if (response.status === 401 || response.status === 403) {
    return (await response.json()) as UnauthenticatedSession;
  }

  if (!response.ok) {
    throw new Error(await readErrorMessage(response, "Не удалось получить сессию платформы"));
  }

  return (await response.json()) as AuthenticatedSession;
}

export async function fetchAvailableApps(): Promise<LauncherAuthApp[]> {
  const response = await fetch("/api/apps", { cache: "no-store" });

  if (!response.ok) {
    throw new Error(await readErrorMessage(response, "Не удалось получить список приложений"));
  }

  const payload = (await response.json()) as { apps?: LauncherAuthApp[] };
  return payload.apps ?? [];
}

async function readErrorMessage(response: Response, fallback: string) {
  try {
    const payload = (await response.json()) as { error?: string };
    return payload.error ?? fallback;
  } catch {
    return response.statusText || fallback;
  }
}
