import { type Group } from './groups';

export const getPlayer = async ({
  token,
  username = ''
}: {
  token: string;
  username?: string;
}): Promise<Player | null> => {
  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/player/${username}`, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });

  const player = (await res.json()) as Player;

  if (!res.ok) {
    throw new Error('Failed to fetch player');
  }

  if (!player) {
    return null;
  }

  return player;
};

export type Player = {
  email: string;
  pseudo: string;
  firstnames: string;
  lastname: string;
  description: string;
  avatar: string;
  groups: Group[];
  score: number;
  tries: number;
  completions: number;
  rank: number;
  completionsList: Completion[];
  badges: Badge[] | null;
};

export type Badge = {
  name: string;
  level: number;
  logo?: string;
};

export type Completion = {
  puzzleName: string;
  tries: number;
  score: number;
};
