import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import apiClient from '../api/client'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const accessToken = ref(null)
  const masterKeySalt = ref(null)

  const isAuthenticated = computed(() => !!accessToken.value)
  const isAdmin = computed(() => user.value?.role === 'admin')
  const hasEmailAccounts = computed(() => (user.value?.email_account_count || 0) > 0)

  async function login(username, password) {
    const response = await apiClient.post('/auth/login', { username, password })
    user.value = response.data.user
    accessToken.value = response.data.access_token
    masterKeySalt.value = response.data.master_key_salt
    return response.data
  }

  async function register(username, password, email, inviteToken) {
    const payload = { username, password }
    if (email) payload.email = email
    if (inviteToken) payload.invite_token = inviteToken
    const response = await apiClient.post('/auth/register', payload)
    user.value = response.data.user
    accessToken.value = response.data.access_token
    return response.data
  }

  async function refreshToken() {
    const response = await apiClient.post('/auth/refresh')
    accessToken.value = response.data.access_token
    return response.data.access_token
  }

  async function fetchMe() {
    const response = await apiClient.get('/auth/me')
    user.value = response.data
    masterKeySalt.value = response.data.master_key_salt
    return response.data
  }

  async function changePassword(currentPassword, newPassword) {
    await apiClient.post('/auth/change-password', {
      current_password: currentPassword,
      new_password: newPassword,
    })
  }

  function logout() {
    apiClient.post('/auth/logout').catch(() => {})
    user.value = null
    accessToken.value = null
    masterKeySalt.value = null
  }

  return {
    user,
    accessToken,
    masterKeySalt,
    isAuthenticated,
    isAdmin,
    hasEmailAccounts,
    login,
    register,
    refreshToken,
    fetchMe,
    changePassword,
    logout,
  }
})
