import { create } from 'zustand'
import { authClient } from '@/lib/auth-client'
import AsyncStorage from '@react-native-async-storage/async-storage'

interface Session {
  user: { id: string; email: string; name: string; mustChangePassword?: boolean }
}

interface AuthState {
  session: Session | null
  isInitialized: boolean
  initialize: () => Promise<void>
  setSession: (session: Session | null, token?: string) => Promise<void>
  signOut: () => Promise<void>
}

export const useAuthStore = create<AuthState>((set) => ({
  session: null,
  isInitialized: false,

  initialize: async () => {
    try {
      // Check if we have a stored token and validate it
      const token = await AsyncStorage.getItem('better-auth-session')
      if (!token) {
        set({ session: null, isInitialized: true })
        return
      }
      // authClient now sends the token via cookie header (see auth-client.ts)
      const result = await authClient.getSession()
      if (result?.data?.user) {
        const u = result.data.user as any
        set({
          session: {
            user: {
              id: u.id,
              email: u.email,
              name: u.name,
              mustChangePassword: u.mustChangePassword ?? false,
            },
          },
          isInitialized: true,
        })
      } else {
        await AsyncStorage.removeItem('better-auth-session')
        set({ session: null, isInitialized: true })
      }
    } catch {
      set({ session: null, isInitialized: true })
    }
  },

  setSession: async (session, token) => {
    if (token) {
      await AsyncStorage.setItem('better-auth-session', token)
    }
    set({ session })
  },

  signOut: async () => {
    await authClient.signOut()
    await AsyncStorage.removeItem('better-auth-session')
    set({ session: null })
  },
}))
