import type { Project, RepoDefinition } from "$lib/types/project";

export async function resolveProjectData(repo: RepoDefinition): Promise<Project> {
  const { id, full_name: fullName } = repo;
  let full_name_p = fullName.split("/")
  const name = full_name_p[1] ?? fullName;

  let description;
  const repoResponse = await fetch(`https://api.github.com/repos/${fullName}`);
  if (repoResponse.ok) {
    const repoData = await repoResponse.json();
    description = repoData.description ?? `by ${full_name_p[0]}`;
  }

  let thumbnail = `https://raw.githubusercontent.com/${fullName}/HEAD/thumbnail.webp`
  const thumbResponse = await fetch(thumbnail, { method: 'HEAD' });
  if (!thumbResponse.ok) {
    thumbnail = `https://picsum.photos/seed/${encodeURIComponent(fullName.replaceAll("/", "-"))}/400/225`;
  }

  return {
    id,
    full_name: fullName,
    name,
    thumbnail,
    description
  }
}
