// composables/useAuth.ts
import type { User, LoginForm, RegisterForm } from '~/types/auth'

export const useAuth = () => {
  const user = useState<User | null>('user', () => null)
  const isAuthenticated = computed(() => !!user.value)
  const loading = ref(false)

  const login = async (credentials: LoginForm) => {
    loading.value = true
    try {
      const response = await $fetch<{ user: User; token: string }>(
        'https://easysite102.ru/api/auth/login',
        {
          method: 'POST',
          body: credentials
        }
      )

      user.value = response.user
      // Сохраняем токен в localStorage или cookies
      localStorage.setItem('auth_token', response.token)

      return response
    // eslint-disable-next-line no-useless-catch
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  const register = async (userData: RegisterForm) => {
    loading.value = true
    try {
      const { passwordConfirm, ...registerData } = userData
      const full_name = `${userData.first_name} ${userData.last_name}`

      const response = await $fetch<{ user: User }>(
        'https://easysite102.ru/api/auth/register',
        {
          method: 'POST',
          body: {
            ...registerData,
            full_name
          }
        }
      )

      return response
    // eslint-disable-next-line no-useless-catch
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  const logout = async () => {
    try {
      await $fetch('https://easysite102.ru/api/auth/logout', {
        method: 'POST'
      })
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      user.value = null
      localStorage.removeItem('auth_token')
      await navigateTo('/auth/login')
    }
  }

  const checkAuth = async () => {
    const token = localStorage.getItem('auth_token')
    if (!token) return

    try {
      const response = await $fetch<{ user: User }>(
        'https://easysite102.ru/api/auth/me',
        {
          headers: {
            Authorization: `Bearer ${token}`
          }
        }
      )
      user.value = response.user
    } catch (error) {
      console.error('Auth check failed:', error)
      localStorage.removeItem('auth_token')
    }
  }

  return {
    user: readonly(user),
    isAuthenticated,
    loading: readonly(loading),
    login,
    register,
    logout,
    checkAuth
  }
}