import { ref } from 'vue'

interface User {
  id: number
  email: string
  name: string
  avatar?: string
}

interface LoginData {
  email: string
  password: string
}

interface RegisterData {
  name: string
  email: string
  password: string
  passwordConfirmation: string
}

export const useAuth = () => {
  const user = ref<User | null>(null)
  const isAuthenticated = ref(false)

  // Мок-функция входа
  const login = async (credentials: LoginData): Promise<User> => {
    // В реальном приложении здесь будет запрос к API
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (credentials.email === 'user@example.com' && credentials.password === 'password') {
          const mockUser: User = {
            id: 1,
            email: credentials.email,
            name: 'Иван Иванов'
          }
          user.value = mockUser
          isAuthenticated.value = true
          localStorage.setItem('user', JSON.stringify(mockUser))
          resolve(mockUser)
        } else {
          reject(new Error('Неверные учетные данные'))
        }
      }, 1000)
    })
  }

  // Мок-функция регистрации
  const register = async (data: RegisterData): Promise<User> => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockUser: User = {
          id: Date.now(),
          email: data.email,
          name: data.name
        }
        user.value = mockUser
        isAuthenticated.value = true
        localStorage.setItem('user', JSON.stringify(mockUser))
        resolve(mockUser)
      }, 1000)
    })
  }

  // Выход
  const logout = async (): Promise<void> => {
    return new Promise((resolve) => {
      setTimeout(() => {
        user.value = null
        isAuthenticated.value = false
        localStorage.removeItem('user')
        resolve()
      }, 500)
    })
  }

  // Проверка авторизации при загрузке
  const checkAuth = () => {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      user.value = JSON.parse(storedUser)
      isAuthenticated.value = true
    }
  }

  return {
    user,
    isAuthenticated,
    login,
    register,
    logout,
    checkAuth
  }
}