export const MARKETPLACE_AUTH_STATE_KEY = 'marketplace-auth-state'

export function buildMarketplaceAuthState({ marketplaceId, returnTo } = {}) {
  return btoa(
    JSON.stringify({
      marketplaceId,
      returnTo
    })
  )
}

export function parseMarketplaceAuthState(rawState) {
  if (!rawState) {
    return null
  }

  try {
    return JSON.parse(atob(rawState))
  } catch {
    return null
  }
}

export function getMarketplaceCallbackUrl() {
  if (typeof window === 'undefined') {
    return ''
  }

  return `${window.location.origin}/auth/marketplace/callback`
}

export function storeMarketplaceAuthState(rawState, data) {
  if (typeof window === 'undefined' || !rawState) {
    return
  }

  window.sessionStorage.setItem(
    `${MARKETPLACE_AUTH_STATE_KEY}:${rawState}`,
    JSON.stringify(data)
  )
}

export function readMarketplaceAuthState(rawState) {
  if (typeof window === 'undefined' || !rawState) {
    return null
  }

  const stored = window.sessionStorage.getItem(
    `${MARKETPLACE_AUTH_STATE_KEY}:${rawState}`
  )
  if (!stored) {
    return null
  }

  try {
    return JSON.parse(stored)
  } catch {
    return null
  }
}

export function clearMarketplaceAuthState(rawState) {
  if (typeof window === 'undefined' || !rawState) {
    return
  }

  window.sessionStorage.removeItem(`${MARKETPLACE_AUTH_STATE_KEY}:${rawState}`)
}
