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

export const getScores = async ({ token }: { token: string }): Promise<Score[]> => {
  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/leaderboard`, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });

  const scores = (await res.json()) as Score[];

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

  if (!scores) {
    return [];
  }

  return scores;
};

export const getScoresEvent = async ({
  token,
  id
}: {
  token: string;
  id: number;
}): Promise<ScoreEvent> => {
  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/leaderboard/${id}`, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });

  const scores = (await res.json()) as ScoreEvent;

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

  if (!scores) {
    return {} as ScoreEvent;
  }

  return scores as ScoreEvent;
};

export type Score = {
  score: number;
  tries: number;
  completions: number;
  pseudo: string;
  groups: Group[];
  avatar: string;
  rank: number;
};

export type ScoreEvent = {
  start_date: string;
  end_date: string;
  groups: [
    {
      name: string;
      rank: number;
      players: [
        {
          pseudo: string;
          tries: number;
          completion: number;
          score: number;
        }
      ];
    }
  ];
};
