import { SdkBase } from './SdkBase.js'

export type AuthProviders = 'google' | 'github' | 'linkedin'

export interface AuthRedirectOptions {
  /**
   * The path or the full URL
   */
  redirect?: string
  /**
   * The invitation token to register the user in a specific organization.
   */
  token?: string
  /**
   * Whether to `redirect` the current tab or to create a new one
   */
  type?: 'redirect' | 'tab'
}

export class AuthSdk extends SdkBase {
  /**
   * Redirects to the API server to perform authentication for a given provider.
   *
   * @param provider The provider to use
   * @param redirect The path or the full URL
   */
  oauthRedirect(provider: AuthProviders, opts: AuthRedirectOptions = {}): Window | null {
    const { redirect, token, type = 'redirect' } = opts
    const base = new URL(this.sdk.baseUri)
    if (!['google', 'github', 'linkedin'].includes(provider)) {
      throw new Error(`Invalid provider: ${provider}`)
    }
    const url = new URL(`/auth/${provider}/redirect`, base)
    if (redirect) {
      url.searchParams.set('r', redirect)
    }
    if (token) {
      url.searchParams.set('token', token)
    }
    if (type === 'redirect') {
      window.location.href = url.toString()
      return null
    }
    const ref = window.open(url.toString(), '_blank')
    return ref
  }
}
