import { fetchActiveTeamByOwnerId } from './teamsService'
import { SITE_URL } from './utilities'

export function authenticate(): void {
  // MAJOR DOMO - 712002920950005870
  const clientID = '712002920950005870'
  // TODO: dynamically redirect to current view by getting current query params and adding them back on after?
  const redirectURI = encodeURIComponent(SITE_URL)
  const scope = 'identify' // Adjust the scope as needed
  window.location.href = `https://discord.com/oauth2/authorize?client_id=${clientID}&redirect_uri=${redirectURI}&response_type=token&scope=${scope}`
}

export async function isDiscordAuthenticated(): Promise<boolean> {
  const ownerId: string | undefined = getOwnerId()
  if (!ownerId) return false

  return !!(await fetchActiveTeamByOwnerId(ownerId))
}

export function getOwnerId(): string | undefined {
  return parseCookie(document.cookie)?.discord
}

export async function completeAuthentication(): Promise<void> {
  if (!window.location.hash) {
    console.warn('No token hash found in return URL')
    return
  }

  // Extract the access token from the URL params
  const urlParams = new URLSearchParams(window.location.hash.slice(1))
  const accessToken = urlParams.get('access_token')
  const tokenType = urlParams.get('token_type') //should be 'Bearer'
  const userResponse = await fetch('https://discord.com/api/users/@me', {
    headers: {
      authorization: `${tokenType} ${accessToken}`
    }
  })
  if (!userResponse.ok) {
    console.warn('userResponse was not OK', userResponse)
    return
  }
  // right now we only care about the id property but we could make a full discord account object if desired
  const user: { id: string } = await userResponse.json()
  if (!user?.id) {
    console.warn('No user or id found while authenticating')
    return
  }

  window.location.href = SITE_URL
  saveOwnerIdCookie(user.id)
}

// Based on https://www.30secondsofcode.org/js/s/parse-cookie/
export function parseCookie(cookie: string | undefined): { [key: string]: string } {
  if (!cookie) return {}
  return cookie.split(';')
    .map(v => v.split('='))
    .reduce((acc: { [key: string]: string }, v) => {
      acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim())
      return acc
    }, {})
}

export function saveOwnerIdCookie(ownerId: string): void {
  document.cookie = `discord=${ownerId}; expires=Fri, 1 Jan 2100 12:00:00 UTC; path=/`
}

export function clearCookie(): void {
  document.cookie = "discord=;-1;path=/"
}
