// hooks/useAuth.js
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useAuthStore } from '@/stores/authStore'
import { authFetch } from '@/lib/api'

// Auth hooks
export const useLogin = () => {
    const queryClient = useQueryClient()
    const login = useAuthStore.getState().login;

    return useMutation({
        mutationFn: (credentials) =>
            authFetch('/api/auth/login', {
                method: 'POST',
                body: JSON.stringify(credentials),
                credentials: 'include', // For http-only cookies
                headers: {
                    'Content-Type': 'application/json',
                }
            }),
        onSuccess: (data) => {
            const { user, token } = data
            queryClient.invalidateQueries(['user'])
            login(user, token)
        },
    })
}

export const useSignup = () => {
    return useMutation({
        mutationFn: (userData) =>
            authFetch('/api/auth/signup', {
                method: 'POST',
                body: JSON.stringify(userData),
            }),
    })
}

export const useVerifyEmail = () => {
    const queryClient = useQueryClient()

    return useMutation({
        mutationFn: async ({ email, code }) => {
            return authFetch('/api/auth/verify-email', {
                method: 'POST',
                body: JSON.stringify({ email, verificationCode: code }),
            })
        },
        onSuccess: () => {
            queryClient.invalidateQueries(['user'])
        }
    })
}

export const useResendVerification = () => {
    const queryClient = useQueryClient()

    return useMutation({
        mutationFn: async ({ email }) => {
            return authFetch('/api/auth/resend-verification', {
                method: 'POST',
                body: JSON.stringify({ email }),
            })
        },
        onSuccess: () => {
            queryClient.invalidateQueries(['user'])
        }
    })
};

export const useLogout = () => {
    const queryClient = useQueryClient()
    const logout = useAuthStore.getState().logout;

    return useMutation({
        mutationFn: () => authFetch('/api/auth/logout', { method: 'POST' }),
        onSuccess: () => {
            logout()
            queryClient.clear() // Clear all cached queries
            router.push('/login')
        },
    })
}

export const useCurrentUser = () => {
    const { user, token, isAuthenticated } = useAuthStore()

    return useQuery({
        queryKey: ['user'],
        queryFn: async () => {
            if (!isAuthenticated) return null
            return authFetch('/api/profiles/me', {
                headers: { Authorization: `Bearer ${token}` },
            })
        },
        initialData: user,
        enabled: isAuthenticated && !!token,
        staleTime: 5 * 60 * 1000, // 5 minutes
    })
}