import type { Gitea } from "./types"

const giteaUrl = "https://git.nose.space"

export async function fetchPR(fullname: string, prNumber: number): Promise<Gitea.PullRequest> {
  const url = `${giteaUrl}/api/v1/repos/${fullname}/pulls/${prNumber}`
  const response = await fetch(url, {
    headers: {
      Authorization: `token ${process.env.GITEA_API_TOKEN}`,
    },
  })
  if (!response.ok) {
    throw new Error(`Gitea API error: ${response.status} ${response.statusText}`)
  }

  return response.json() as Promise<Gitea.PullRequest>
}

export async function fetchReviewComments(
  fullname: string,
  prNumber: number
): Promise<Gitea.ReviewComment[]> {
  // First, fetch all reviews
  const reviewsUrl = `${giteaUrl}/api/v1/repos/${fullname}/pulls/${prNumber}/reviews`
  const reviewsResponse = await fetch(reviewsUrl, {
    headers: {
      Authorization: `token ${process.env.GITEA_API_TOKEN}`,
    },
  })
  if (!reviewsResponse.ok) {
    throw new Error(`Gitea API error: ${reviewsResponse.status} ${reviewsResponse.statusText}`)
  }

  const reviews = (await reviewsResponse.json()) as Array<{
    id: number
    user: Gitea.User
    body: string
    created_at: string
    html_url: string
    comments_count: number
  }>

  // For each review, fetch its comments
  const allComments: Gitea.ReviewComment[] = []
  for (const review of reviews) {
    if (review.comments_count === 0) continue

    const commentsUrl = `${giteaUrl}/api/v1/repos/${fullname}/pulls/${prNumber}/reviews/${review.id}/comments`
    const commentsResponse = await fetch(commentsUrl, {
      headers: {
        Authorization: `token ${process.env.GITEA_API_TOKEN}`,
      },
    })

    if (commentsResponse.ok) {
      const comments = (await commentsResponse.json()) as Gitea.ReviewComment[]
      allComments.push(...comments)
    }
  }

  return allComments
}
