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

  if (!res.ok) {
    return [];
  }

  const chapters = (await res.json()) as Chapter[];

  if (!chapters) {
    return [];
  }

  return chapters;
};

export const getChapter = async ({
  token,
  id
}: {
  token: string;
  id: number;
}): Promise<Chapter | null> => {
  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/chapter/${id}`, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });

  if (!res.ok) {
    return null;
  }
  const chapter = (await res.json()) as Chapter;

  if (!chapter) {
    return null;
  }

  return chapter;
};

export const getPuzzles = async ({ token }: { token: string }): Promise<Chapter[]> => {
  const chapters = await getChapters({ token });

  if (!chapters) {
    return [];
  }

  for (let i = 0; i < chapters.length; i++) {
    let chapter = chapters[i];
    chapter = (await getChapter({ token, id: chapter.id })) as Chapter;
    if (!chapter) continue;
    chapters[i].puzzles = chapter.puzzles;
  }

  return chapters;
};

export const getPuzzle = async ({
  token,
  id
}: {
  token: string;
  id: number;
}): Promise<Puzzle | null> => {
  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/puzzle/${id}`, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });

  if (!res.ok) {
    return null;
  }

  const puzzle = (await res.json()) as Puzzle;

  if (!puzzle) {
    return null;
  }

  return puzzle;
};

export type Puzzle = {
  id: number;
  name: string;
  content: string;
  scoreMax: number;
  tags: Tag[] | null;
  tries?: number;
  score?: number;
};

export type Chapter = {
  id: number;
  name: string;
  puzzles: Puzzle[];
  startDate?: string;
  endDate?: string;
};

export type Tag = {
  name: string;
};
