import client from "./client"
import type { ApiResponse } from "../types"

export interface OAuthProvider {
  id: string
  name: string
}

export async function getOAuthProviders(): Promise<OAuthProvider[]> {
  try {
    const { data } = await client.get<ApiResponse<OAuthProvider[]>>("/v1/auth/oauth/providers")
    return Array.isArray(data.data) ? data.data : []
  } catch {
    return []
  }
}

export async function getOAuthUrl(pluginId: string, redirectUri: string): Promise<{ url: string; state: string }> {
  const { data } = await client.get<ApiResponse<{ url: string; state: string }>>(
    `/v1/auth/oauth/${encodeURIComponent(pluginId)}/url`,
    { params: { redirect_uri: redirectUri } },
  )
  return data.data as { url: string; state: string }
}

export async function getOAuthConnections(): Promise<{ plugin_id: string; created_at: string }[]> {
  const { data } = await client.get<ApiResponse<{ plugin_id: string; created_at: string }[]>>(
    "/v1/users/me/oauth-connections",
  )
  return Array.isArray(data.data) ? data.data : []
}

export async function unbindOAuth(pluginId: string): Promise<void> {
  await client.delete(`/v1/auth/oauth/${encodeURIComponent(pluginId)}/unbind`)
}
