// stores/auth.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { apiClient, withLoading } from './helpers/api'
import { handleApiError } from './helpers/api';
import { userStore } from './user'

export const useAuthStore = defineStore('auth', () => {
  // State
  const user = ref(null)
  const token = ref(localStorage.getItem('auth_token') || '')
  const loading = ref(false)
  const error = ref('')
  const initialized = ref(false)

  // Getters
  const isAuthenticated = computed(() => !!token.value && !!user.value)
  const userFullName = computed(() =>
    user.value ? `${user.value.firstName} ${user.value.lastName}` : ''
  )

  // Actions
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('auth_token', newToken)
  }

  const clearAuth = () => {
    token.value = ''
    user.value = null
    localStorage.removeItem('auth_token')
  }

  const setUser = (userData) => {
    user.value = userData
  }

  const register = async (userData) => {
    // Передаем store объект с loading и error
    return withLoading({ loading, error }, async () => {
      await apiClient.post('/auth/register', userData)

      // Auto-login after registration
      const loginResponse = await apiClient.post('/auth/login', {
        email: userData.email,
        password: userData.password
      })

      const { token: authToken, user: userInfo } = loginResponse.data
      setToken(authToken)
      setUser(userInfo)

      return { success: true }
    })
  }

  const login = async (credentials) => {
    return withLoading({ loading, error }, async () => {
      const response = await apiClient.post('/auth/login', credentials)
      const { token: authToken, user: userInfo } = response.data

      setToken(authToken)
      setUser(userInfo)

      return { success: true, data: response.data }
    })
  }

  const logout = async () => {
    return withLoading({ loading, error }, async () => {
      try {
        userStore.resetUserStore()
        await apiClient.post('/auth/logout')
      } catch (err) {
        console.error('Logout error:', err)
      } finally {
        clearAuth()
      }
      return { success: true }
    })
  }

  const fetchProfile = async () => {
    return withLoading({ loading, error }, async () => {
      const response = await apiClient.get('/user/profile')
      setUser(response.data)

      console.log('DEBUG - Profile API response:', response.data);
      return { success: true, data: response.data }
    })
  }

  const updateProfile = async (profileData) => {
    return withLoading({ loading, error }, async () => {
      const response = await apiClient.post('/user/editProfile', profileData)
      setUser(response.data)
      return { success: true, data: response.data }
    })
  }

  const initializeAuth = async () => {
    if (initialized.value || !token.value) return

    initialized.value = true

    try {
      await fetchProfile()
      console.log('Auth restored successfully')
    } catch (err) {
      console.error('Auth restoration failed:', err)
      clearAuth()
    }
  }

  const updateAvatar = async (avatarFile) => {
    const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
    if (avatarFile.size > MAX_FILE_SIZE) {
      return {
        success: false,
        error: 'Размер файла не должен превышать 5MB'
      };
    }

    // ✅ ПРОВЕРКА ТИПА ФАЙЛА
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    if (!allowedTypes.includes(avatarFile.type)) {
      return {
        success: false,
        error: 'Допустимые форматы: JPEG, PNG, GIF, '
      };
    }
    const formData = new FormData()
    formData.append('avatar', avatarFile)

    try {
      loading.value = true
      error.value = ''

      const response = await apiClient.post('/user/avatars/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      console.log('Avatar upload response:', response.data)

      // Универсальная обработка ответа
      let result
      if (response.data.success !== undefined) {
        result = response.data
      } else {
        // Если поле success отсутствует, считаем успешным
        result = { success: true, ...response.data }
      }

      if (result.success) {
        // ОБНОВЛЯЕМ ВЕСЬ ПРОФИЛЬ ПОЛЬЗОВАТЕЛЯ
        await fetchProfile()
        return { success: true, avatar: result.avatar }
      } else {
        return { success: false, error: result.error || result.message }
      }

    } catch (error) {
      console.error('Avatar upload error:', error)
      const result = handleApiError(error)
      return result
    } finally {
      loading.value = false
    }
  }

  const deleteAvatar = async () => {
    try {
      const response = await apiClient.delete('/user/avatars/delete')

      if (response.data.success) {
        // Удаляем аватар из стора
        if (user.value) {
          user.value.avatar = null
        }
        return { success: true }
      }
    } catch (error) {
      const result = handleApiError(error)
      return result
    }
  }

  return {
    // State
    user,
    token,
    loading,
    error,
    initialized,

    // Getters
    isAuthenticated,
    userFullName,

    // Actions
    register,
    login,
    logout,
    fetchProfile,
    updateProfile,
    initializeAuth,
    clearAuth,
    updateAvatar,
    deleteAvatar
  }
})