import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { LoginRequest, User } from '@/types'
import { authApi } from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
  // Token persisted to localStorage
  const token = ref<string>(localStorage.getItem('token') || '')

  // User persisted to localStorage (parsed if available)
  const user = ref<User | null>(loadUser())

  const isLoggedIn = computed(() => !!token.value)

  function loadUser(): User | null {
    const raw = localStorage.getItem('user')
    if (!raw) return null
    try {
      return JSON.parse(raw) as User
    } catch {
      return null
    }
  }

  function setToken(newToken: string) {
    token.value = newToken
    if (newToken) {
      localStorage.setItem('token', newToken)
    } else {
      localStorage.removeItem('token')
    }
  }

  function setUser(newUser: User | null) {
    user.value = newUser
    if (newUser) {
      localStorage.setItem('user', JSON.stringify(newUser))
    } else {
      localStorage.removeItem('user')
    }
  }

  async function login(payload: LoginRequest) {
    const res = await authApi.login(payload) as any;
    const accessToken: string = res.accessToken ?? res.data?.accessToken ?? '';
    const userData: User | null = res.user ?? res.data?.user ?? null;
    if (accessToken) setToken(accessToken);
    if (userData) setUser(userData);
    return res;
  }

  async function fetchCurrentUser() {
    const current = await authApi.getCurrentUser()
    setUser(current)
    return current
  }

  async function logout() {
    try {
      await authApi.logout()
    } catch {
      // Ignore network errors during logout
    }
    setToken('')
    setUser(null)
  }

  return {
    token,
    user,
    isLoggedIn,
    login,
    fetchCurrentUser,
    logout,
  }
})
