import type { DriveMountOAuthProvider } from "@/lib/api/types"

export const DRIVE_MOUNT_OAUTH_CALLBACK_PATH = "/drive/mounts/oauth/callback"

export function buildDriveMountOAuthRedirectURI(origin?: string): string {
  const base = (origin ?? (typeof window !== "undefined" ? window.location.origin : "")).replace(/\/$/, "")
  if (!base) return DRIVE_MOUNT_OAUTH_CALLBACK_PATH
  return `${base}${DRIVE_MOUNT_OAUTH_CALLBACK_PATH}`
}

const BACKEND_TO_PROVIDER: Record<string, DriveMountOAuthProvider> = {
  googledrive: "google",
  google: "google",
  dropbox: "dropbox",
  onedrive: "microsoft",
  microsoft: "microsoft",
}

export function driveMountOAuthProvider(backendType: string): DriveMountOAuthProvider | null {
  return BACKEND_TO_PROVIDER[backendType.toLowerCase()] ?? null
}

export function isDriveMountOAuthConfigured(
  backendType: string,
  configured: DriveMountOAuthProvider[] | undefined
): boolean {
  const provider = driveMountOAuthProvider(backendType)
  if (!provider) return true
  return configured?.includes(provider) ?? false
}

export function openDriveMountOAuthPopup(oauthUrl: string, mountId: string) {
  const width = 600
  const height = 720
  const left = window.screenX + (window.outerWidth - width) / 2
  const top = window.screenY + (window.outerHeight - height) / 2
  const state = encodeURIComponent(mountId)
  const url = oauthUrl.includes("state=")
    ? oauthUrl
    : `${oauthUrl}${oauthUrl.includes("?") ? "&" : "?"}state=${state}`
  window.open(
    url,
    "drive-mount-oauth",
    `width=${width},height=${height},left=${left},top=${top},noopener,noreferrer`
  )
}
