import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { SessionUser, GitHubUser } from '@/api/types'

export const useAuthStore = defineStore('auth', () => {
  const user = ref<SessionUser | null>(null)
  const org = ref('')
  const orgs = ref<string[]>([])
  const permissions = ref<string[]>([])
  const githubUser = ref<GitHubUser | null>(null)
  const posthogKey = ref('')
  const posthogHost = ref('')
  const authEnabled = ref(true)

  const isAuthenticated = computed(() => user.value !== null)
  const hasGitHub = computed(() => githubUser.value !== null)

  function init() {
    const session = window.__SPECWRIGHT__
    if (!session) return
    user.value = session.user
    org.value = session.org
    orgs.value = session.orgs
    permissions.value = session.permissions
    githubUser.value = session.github_user
    posthogKey.value = session.posthog_key
    posthogHost.value = session.posthog_host
    authEnabled.value = session.auth_enabled ?? true
  }

  function hasPermission(permission: string): boolean {
    return permissions.value.includes(permission)
  }

  function setOrg(newOrg: string) {
    org.value = newOrg
  }

  return {
    user,
    org,
    orgs,
    permissions,
    githubUser,
    posthogKey,
    posthogHost,
    authEnabled,
    isAuthenticated,
    hasGitHub,
    init,
    hasPermission,
    setOrg,
  }
})
