import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import api from '@/lib/api';
import type { User } from '@/types';

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

    const isAuthenticated = computed(() => !!user.value);
    const userName = computed(() => user.value?.name ?? '');
    const userRoles = computed(() => user.value?.roles ?? []);
    const userPermissions = computed(() => user.value?.permissions ?? []);

    function hasRole(role: string): boolean {
        return userRoles.value.includes(role);
    }

    function hasPermission(permission: string): boolean {
        return userPermissions.value.includes(permission);
    }

    function hasAnyRole(roles: string[]): boolean {
        return roles.some(r => userRoles.value.includes(r));
    }

    async function fetchUser() {
        try {
            loading.value = true;
            const response = await api.get('/user');
            user.value = response.data.user;
        } catch {
            user.value = null;
        } finally {
            loading.value = false;
            initialized.value = true;
        }
    }

    async function login(email: string, password: string) {
        loading.value = true;
        try {
            // First, get CSRF cookie from Sanctum
            await api.get('/sanctum/csrf-cookie', { baseURL: '' });
            const response = await api.post('/login', { email, password });
            user.value = response.data.user;
            return { success: true };
        } catch (error: any) {
            const message = error.response?.data?.message || 'Login gagal.';
            return { success: false, message };
        } finally {
            loading.value = false;
        }
    }

    async function logout() {
        try {
            await api.post('/logout');
        } finally {
            user.value = null;
            // Full page reload to clear all state
            window.location.href = '/login';
        }
    }

    return {
        user,
        loading,
        initialized,
        isAuthenticated,
        userName,
        userRoles,
        userPermissions,
        hasRole,
        hasPermission,
        hasAnyRole,
        fetchUser,
        login,
        logout,
    };
});
