import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { api } from '@/api'

export interface User {
  id: string
  email: string
  role: 'chef' | 'disponent' | 'mitarbeiter'
  first_name: string
  last_name: string
  org_id: string
}

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const accessToken = ref<string | null>(localStorage.getItem('accessToken'))
  const refreshToken = ref<string | null>(localStorage.getItem('refreshToken'))
  const orgSlug = ref<string>(localStorage.getItem('orgSlug') || '')

  const isAuthenticated = computed(() => !!user.value && !!accessToken.value)
  const hasStoredToken = computed(() => !!accessToken.value)
  const isChef = computed(() => user.value?.role === 'chef')
  const isDisponent = computed(() => user.value?.role === 'disponent')
  const isMitarbeiter = computed(() => user.value?.role === 'mitarbeiter')
  const canManageUsers = computed(() => isChef.value || isDisponent.value)
  const canManageOrders = computed(() => isChef.value || isDisponent.value)
  const fullName = computed(() => user.value ? `${user.value.first_name} ${user.value.last_name}` : '')

  function setTokens(access: string, refresh: string) {
    accessToken.value = access
    refreshToken.value = refresh
    localStorage.setItem('accessToken', access)
    localStorage.setItem('refreshToken', refresh)
  }

  function setOrgSlug(slug: string) {
    orgSlug.value = slug
    localStorage.setItem('orgSlug', slug)
  }

  function clearAuth() {
    user.value = null
    accessToken.value = null
    refreshToken.value = null
    localStorage.removeItem('accessToken')
    localStorage.removeItem('refreshToken')
  }

  async function login(email: string, password: string, org: string) {
    const response = await api.post('/auth/login', {
      email,
      password,
      org_slug: org
    })
    
    setTokens(response.data.accessToken, response.data.refreshToken)
    setOrgSlug(org)
    user.value = response.data.user
    
    return response.data
  }

  async function register(data: {
    email: string
    password: string
    first_name: string
    last_name: string
    phone?: string
    org_slug: string
  }) {
    const response = await api.post('/auth/register', data)
    return response.data
  }

  async function logout() {
    try {
      await api.post('/auth/logout')
    } catch {
      // Ignore errors
    }
    clearAuth()
  }

  async function fetchCurrentUser() {
    try {
      const response = await api.get('/auth/me')
      user.value = response.data.user
    } catch {
      clearAuth()
    }
  }

  async function refreshAccessToken() {
    if (!refreshToken.value) {
      throw new Error('No refresh token')
    }
    
    const response = await api.post('/auth/refresh', {
      refreshToken: refreshToken.value
    })
    
    accessToken.value = response.data.accessToken
    localStorage.setItem('accessToken', response.data.accessToken)
    
    return response.data.accessToken
  }

  return {
    user,
    accessToken,
    refreshToken,
    orgSlug,
    isAuthenticated,
    hasStoredToken,
    isChef,
    isDisponent,
    isMitarbeiter,
    canManageUsers,
    canManageOrders,
    fullName,
    login,
    register,
    logout,
    fetchCurrentUser,
    refreshAccessToken,
    setOrgSlug
  }
})
