import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { api } from '../composables/useApi'

const DEFAULT_USER = {
  id: null,
  role: 'viewer',
  username: 'anonymous',
  display_name: '匿名',
  has_password: false,
  business_verified: false,
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('oil_auth_token') || '')
  const user = ref({ ...DEFAULT_USER })

  // Getters
  const isLoggedIn = computed(() => user.value.id !== null)
  const isAdmin = computed(() => user.value.role === 'admin')
  const canManage = computed(() =>
    ['senior_editor', 'admin'].includes(user.value.role)
  )
  const canEdit = computed(() =>
    ['editor', 'senior_editor', 'admin'].includes(user.value.role)
  )
  const isBusiness = computed(() => user.value.business_verified)

  // Actions
  async function initToken() {
    if (token.value) {
      await loadMe()
    }
  }

  async function loadMe() {
    try {
      const data = await api.get('/api/me')
      user.value = {
        id: data.id,
        role: data.role,
        username: data.username,
        display_name: data.display_name,
        has_password: data.has_password ?? false,
        business_verified: data.business_verified ?? false,
      }
    } catch {
      logout()
    }
  }

  async function login(username, password) {
    const data = await api.post('/api/login', { username, password })
    token.value = data.token
    localStorage.setItem('oil_auth_token', data.token)
    await loadMe()
  }

  async function register(username, password, displayName) {
    const data = await api.post('/api/register', {
      username,
      password,
      display_name: displayName,
    })
    token.value = data.token
    localStorage.setItem('oil_auth_token', data.token)
    await loadMe()
  }

  function logout() {
    token.value = ''
    localStorage.removeItem('oil_auth_token')
    user.value = { ...DEFAULT_USER }
  }

  function canEditRecipe() {
    return canEdit.value
  }

  return {
    token,
    user,
    isLoggedIn,
    isAdmin,
    canManage,
    canEdit,
    isBusiness,
    initToken,
    loadMe,
    login,
    register,
    logout,
    canEditRecipe,
  }
})
