/**
 * User profile store.
 *
 * Manages extended user profile data beyond basic auth info.
 * Includes linked accounts, collection stats, and profile settings.
 */
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

import { config } from '@/config'
import { useAuthStore } from './auth'

export interface LinkedAccount {
  provider: 'google' | 'discord'
  providerUserId: string
  email: string | null
  linkedAt: string
}

export interface UserProfile {
  id: string
  displayName: string
  avatarUrl: string | null
  hasStarterDeck: boolean
  createdAt: string
  linkedAccounts: LinkedAccount[]
}

export const useUserStore = defineStore('user', () => {
  // State
  const profile = ref<UserProfile | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // Getters
  const displayName = computed(() => profile.value?.displayName ?? 'Unknown')
  const avatarUrl = computed(() => profile.value?.avatarUrl)
  const hasStarterDeck = computed(() => profile.value?.hasStarterDeck ?? false)
  const linkedAccounts = computed(() => profile.value?.linkedAccounts ?? [])

  /**
   * Fetch the current user's profile from the API.
   */
  async function fetchProfile(): Promise<boolean> {
    const auth = useAuthStore()
    const token = await auth.getValidToken()

    if (!token) {
      error.value = 'Not authenticated'
      return false
    }

    isLoading.value = true
    error.value = null

    try {
      const response = await fetch(`${config.apiBaseUrl}/api/users/me`, {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      })

      if (!response.ok) {
        throw new Error('Failed to fetch profile')
      }

      const data = await response.json()
      profile.value = {
        id: data.id,
        displayName: data.display_name,
        avatarUrl: data.avatar_url,
        hasStarterDeck: data.has_starter_deck,
        createdAt: data.created_at,
        linkedAccounts: data.linked_accounts?.map((acc: Record<string, unknown>) => ({
          provider: acc.provider,
          providerUserId: acc.provider_user_id,
          email: acc.email,
          linkedAt: acc.linked_at,
        })) ?? [],
      }

      // Also update auth store's user ref for guards
      auth.setUser({
        id: profile.value.id,
        displayName: profile.value.displayName,
        avatarUrl: profile.value.avatarUrl,
        hasStarterDeck: profile.value.hasStarterDeck,
      })

      return true
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Failed to fetch profile'
      return false
    } finally {
      isLoading.value = false
    }
  }

  /**
   * Update the user's display name.
   */
  async function updateDisplayName(newName: string): Promise<boolean> {
    const auth = useAuthStore()
    const token = await auth.getValidToken()

    if (!token) {
      error.value = 'Not authenticated'
      return false
    }

    isLoading.value = true
    error.value = null

    try {
      const response = await fetch(`${config.apiBaseUrl}/api/users/me`, {
        method: 'PATCH',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ display_name: newName }),
      })

      if (!response.ok) {
        throw new Error('Failed to update profile')
      }

      // Refetch to get updated data
      await fetchProfile()
      return true
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Failed to update profile'
      return false
    } finally {
      isLoading.value = false
    }
  }

  /**
   * Clear profile data on logout.
   */
  function clear(): void {
    profile.value = null
    error.value = null
  }

  return {
    // State
    profile,
    isLoading,
    error,
    // Getters
    displayName,
    avatarUrl,
    hasStarterDeck,
    linkedAccounts,
    // Actions
    fetchProfile,
    updateDisplayName,
    clear,
  }
})
