import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export interface User {
  id: string
  displayName: string
  avatarUrl: string | null
  hasStarterDeck: boolean
}

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  const isAuthenticated = computed(() => !!token.value)

  async function login(username: string, password: string): Promise<boolean> {
    isLoading.value = true
    error.value = null

    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password }),
      })

      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.detail || 'Login failed')
      }

      const data = await response.json()
      token.value = data.access_token
      user.value = data.user
      // Note: localStorage is used for token persistence across page reloads.
      // This is standard for SPAs but tokens are accessible to XSS. The backend
      // should use short-lived access tokens + httpOnly refresh cookies for
      // production. See: https://auth0.com/docs/secure/security-guidance/data-security/token-storage
      localStorage.setItem('auth_token', data.access_token)

      return true
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Login failed'
      return false
    } finally {
      isLoading.value = false
    }
  }

  async function register(
    username: string,
    email: string,
    password: string
  ): Promise<boolean> {
    isLoading.value = true
    error.value = null

    try {
      const response = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, email, password }),
      })

      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.detail || 'Registration failed')
      }

      // Auto-login after registration
      return await login(username, password)
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Registration failed'
      return false
    } finally {
      isLoading.value = false
    }
  }

  function logout() {
    user.value = null
    token.value = null
    localStorage.removeItem('auth_token')
  }

  // Restore token from localStorage on init
  function init() {
    const storedToken = localStorage.getItem('auth_token')
    if (storedToken) {
      token.value = storedToken
      // TODO: Validate token and fetch user profile
    }
  }

  return {
    user,
    token,
    isLoading,
    error,
    isAuthenticated,
    login,
    register,
    logout,
    init,
  }
}, {
  persist: {
    pick: ['token'],
  },
})
