import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { api, type ServerError } from 'boot/axios'

interface User {
  id: string
  email?: string
  username: string
  first_name?: string
  last_name?: string
  avatar?: string
}

const ENDPOINT_MAP = {
  register: '/auth/register',
  forgot: '/auth/forgot',
  change: '/auth/change'
} as const

export type AuthFlowType = keyof typeof ENDPOINT_MAP

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const isInitialized = ref(false)

  const isAuthenticated = computed(() => !!user.value)

  const initialize = async () => {
    try {
      const { data } = await api.get('/customer/profile')
      user.value = data.data
    } catch (error) {
      handleAuthError(error as ServerError)
    } finally {
      isInitialized.value = true
    }
  }

  const handleAuthError = (error: ServerError) => {
    if (error.code === '401') {
      user.value = null
    } else {
      console.error('Authentication error:', error)
    }
  }

  const loginWithCredentials = async (email: string, password: string) => {
    await api.post('/auth/email', { email, password }, { withCredentials: true })
    await initialize()
  }

  const loginWithTelegram = async (initData: string) => {
    await api.post('/auth/telegram', { initData }, { withCredentials: true })
    await initialize()
  }

  const logout = async () => {
    try {
      await api.get('/auth/logout', {})
      user.value = null
      isInitialized.value = false
    } finally {
      // @ts-expect-ignore
      // window.Telegram?.WebApp.close()
    }
  }
  
  const initRegistration = async (flowType: AuthFlowType, email: string) => {
    await api.post(ENDPOINT_MAP[flowType], { email })
  }
  
  const confirmCode = async (flowType: AuthFlowType, email: string, code: string) => {
    await api.post(ENDPOINT_MAP[flowType], { email, code })
  }

  const setPassword = async (
    flowType: AuthFlowType,
    email: string,
    code: string,
    password: string
  ) => {
    await api.post(ENDPOINT_MAP[flowType], { email, code, password })
  }
  
  return {
    user,
    isAuthenticated,
    isInitialized,
    initialize,
    loginWithCredentials,
    loginWithTelegram,
    logout,
    initRegistration,
    confirmCode,
    setPassword
  }
})