import { ref, computed } from 'vue'
import api from '../axios.js'

const user = ref(null)
const loading = ref(false)
const fetched = ref(false)

export function useAuth() {
    const isAuthenticated = computed(() => user.value !== null)

    const userTier = computed(() => {
        if (!user.value) {
            return 'guest'
        }
        return user.value.tier ?? 'free'
    })

    const isPaidTier = computed(() => {
        return ['basic', 'plus', 'pro'].includes(userTier.value)
    })

    const subscriptionCancelled = computed(() => {
        return user.value?.subscription_cancelled ?? false
    })

    const subscriptionCadence = computed(() => {
        return user.value?.subscription_cadence ?? null
    })

    const subscribedAt = computed(() => {
        return user.value?.subscribed_at ?? null
    })

    const subscriptionExpiresAt = computed(() => {
        return user.value?.subscription_expires_at ?? null
    })

    async function fetchUser() {
        if (fetched.value) {
            return
        }
        loading.value = true
        try {
            const response = await api.get('/auth/me')
            user.value = response.data
        } catch {
            user.value = null
        } finally {
            loading.value = false
            fetched.value = true
        }
    }

    function clearUser() {
        user.value = null
        fetched.value = false
    }

    async function logout() {
        try {
            await api.post('/auth/logout')
        } finally {
            clearUser()
        }
    }

    async function updateProfile(data) {
        const response = await api.put('/user/profile', data)
        user.value = response.data
    }

    async function updatePassword(data) {
        await api.put('/user/password', data)
    }

    async function deleteAccount(password) {
        await api.delete('/user', { data: { password } })
        clearUser()
    }

    return {
        user,
        loading,
        isAuthenticated,
        userTier,
        isPaidTier,
        subscriptionCancelled,
        subscriptionCadence,
        subscribedAt,
        subscriptionExpiresAt,
        fetchUser,
        clearUser,
        logout,
        updateProfile,
        updatePassword,
        deleteAccount,
    }
}
