import { useQuery } from '@tanstack/react-query';
import { config } from '../../config';
import { useAuthStore } from '../../auth/auth-store';

export interface RoleSummary {
  id: string;
  name: string;
  system: boolean;
  source: string;
}

export interface GroupSummary {
  id: string;
  name: string;
}

export interface UserDetail {
  userId: string;
  provider: string;
  email: string;
  displayName: string;
  createdAt: string;
  directRoles: RoleSummary[];
  directGroups: GroupSummary[];
  effectiveRoles: RoleSummary[];
  effectiveGroups: GroupSummary[];
}

async function fetchMe(): Promise<UserDetail> {
  const token = useAuthStore.getState().accessToken;
  const res = await fetch(`${config.apiBaseUrl}/auth/me`, {
    headers: {
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      'X-Cameleer-Protocol-Version': '1',
    },
  });
  if (!res.ok) throw new Error(`API error: ${res.status}`);
  return res.json();
}

export function useMe(enabled = false) {
  return useQuery({
    queryKey: ['auth', 'me'],
    queryFn: fetchMe,
    enabled,
    staleTime: 30_000,
  });
}
