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

export const useUserStore = defineStore('user', () => {
  const id = ref<number | null>(null)
  const login = ref('')
  const email = ref('')
  const role = ref('')
  const language = ref('en')

  async function fetchProfile() {
    try {
      const res = await fetch('/api/profile')
      if (res.ok) {
        const data = await res.json()
        id.value = data.id
        login.value = data.login
        email.value = data.email
        role.value = data.role
        language.value = data.language || 'en'
        return true
      }
    } catch (e) {
      console.error('Failed to load profile', e)
    }
    return false
  }

  async function updateProfile(updates: { email?: string; password?: string; language?: string }) {
    const res = await fetch('/api/profile', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updates)
    })
    if (res.ok) {
      if (updates.language) language.value = updates.language
      if (updates.email) email.value = updates.email
      return true
    }
    return false
  }

  function clear() {
    id.value = null
    login.value = ''
    email.value = ''
    role.value = ''
    language.value = 'en'
  }

  return { id, login, email, role, language, fetchProfile, updateProfile, clear }
})
