import * as Sentry from "@sentry/nextjs"
import { ActionResponse, createErrorResponse, createSuccessResponse } from "../action-response"
import { GitHubUserSearchResult } from "../types"

export class GithubService {
  /**
   * Search for GitHub users by username and return their GitHub User ID
   */
  public async searchGitHubUsers(
    searchQuery: string,
  ): Promise<ActionResponse<GitHubUserSearchResult[]>> {
    try {
      if (!searchQuery || searchQuery.trim().length === 0) {
        return createErrorResponse("Search query is required")
      }

      // Call GitHub API to search users
      const response = await this.fetchGithubUsers(searchQuery)

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}))
        return createErrorResponse(errorData.message || "Failed to search GitHub users")
      }

      const data = await response.json()

      return createSuccessResponse(this.mapGitHubUserSearchResult(data.items))
    } catch (error) {
      console.error("Failed to search GitHub users:", error)
      Sentry.captureException("GitHub SearchByName API request failed:" + error, {
        extra: {
          searchQuery,
        },
      })
      return createErrorResponse(
        "We couldn't complete your GitHub search right now. Please try again later.",
      )
    }
  }
  private mapGitHubUserSearchResult(githubUsers: any): GitHubUserSearchResult[] {
    return githubUsers.map((user: any) => ({
      username: user.login,
      githubUserId: user.id,
      avatarUrl: user.avatar_url,
    }))
  }
  private async fetchGithubUsers(searchQuery: string): Promise<Response> {
    return fetch(
      `https://api.github.com/search/users?q=${encodeURIComponent(searchQuery)}&per_page=10`,
      {
        headers: {
          Accept: "application/vnd.github.v3+json",
          ...(process.env.GITHUB_TOKEN && {
            Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
          }),
        },
      },
    )
  }
}
export const githubService = new GithubService()
