import { ref, computed } from 'vue';
import axios from 'axios';
import { UserTypes, ADMIN_ROLES, STAFF_ROLES } from '../../utils/UserTypes.js';
import { useUserStore } from '../../stores/user.js';

const globalRole = ref(sessionStorage.getItem('user_acct_type') || UserTypes.PUBLIC);
const isFetching = ref(false);

async function fetchRole() {
    if (isFetching.value) return;
    const cached = sessionStorage.getItem('user_acct_type');
    if (cached && cached !== UserTypes.PUBLIC) return;

    isFetching.value = true;
    try {
        const response = await axios.get('/get/user/acct-type');
        let acctType = response.data?.acct_type;
        if (acctType && typeof acctType === 'object' && acctType.value) acctType = acctType.value;
        if (acctType) {
            globalRole.value = acctType;
            sessionStorage.setItem('user_acct_type', acctType);
        }
    } catch (error) {
        if (error.response?.status === 401) {
            globalRole.value = UserTypes.PUBLIC;
            sessionStorage.setItem('user_acct_type', UserTypes.PUBLIC);
        }
    } finally {
        isFetching.value = false;
    }
}

if (!sessionStorage.getItem('user_acct_type') || sessionStorage.getItem('user_acct_type') === UserTypes.PUBLIC) {
    fetchRole();
}

export function resetRole() {
    globalRole.value = UserTypes.PUBLIC;
    isFetching.value = false;
    sessionStorage.removeItem('user_acct_type');
}

export function useAuth(user = null) {
    const userStore = useUserStore();

    const currentUser = computed(() => {
        if (user?.value ?? user) return user?.value ?? user;
        const storeUser = userStore.user;
        if (storeUser && Object.keys(storeUser).length > 0) return storeUser;
        try {
            const stored = sessionStorage.getItem('currentUser');
            return stored ? JSON.parse(stored) : null;
        } catch {
            return null;
        }
    });

    const role = computed(() => {
        const localRole = userStore.acctType || currentUser.value?.acct_type;
        if (localRole) {
            if (typeof localRole === 'object' && localRole.value) return localRole.value;
            return localRole;
        }
        return globalRole.value;
    });

    const hasRole = (targetRole) => {
        if (Array.isArray(targetRole)) return targetRole.some(r => role.value === r);
        return role.value === targetRole;
    };

    // Barangay-specific role helpers
    const isSuperAdmin      = computed(() => role.value === UserTypes.SUPER_ADMIN);
    const isPunongBarangay  = computed(() => role.value === UserTypes.PUNONG_BARANGAY);
    const isKagawad         = computed(() => role.value === UserTypes.KAGAWAD);
    const isSecretary       = computed(() => role.value === UserTypes.SECRETARY);
    const isTreasurer       = computed(() => role.value === UserTypes.TREASURER);
    const isSkChairperson   = computed(() => role.value === UserTypes.SK_CHAIRPERSON);
    const isSkCouncilor     = computed(() => role.value === UserTypes.SK_COUNCILOR);
    const isTanod           = computed(() => role.value === UserTypes.TANOD);
    const isBhw             = computed(() => role.value === UserTypes.BHW);
    const isDaycareWorker   = computed(() => role.value === UserTypes.DAYCARE_WORKER);
    const isStaff           = computed(() => role.value === UserTypes.STAFF);
    const isResident        = computed(() => role.value === UserTypes.RESIDENT);
    const isAudit           = computed(() => role.value === UserTypes.AUDIT);
    const isPublic          = computed(() => role.value === UserTypes.PUBLIC || !userStore.isLoggedIn);
    const isLoggedIn        = computed(() => userStore.isLoggedIn);

    // Group helpers
    const isAdmin           = computed(() => ADMIN_ROLES.includes(role.value));
    const isBarangayStaff   = computed(() => STAFF_ROLES.includes(role.value));

    return {
        user: currentUser,
        role,
        hasRole,
        isSuperAdmin,
        isPunongBarangay,
        isKagawad,
        isSecretary,
        isTreasurer,
        isSkChairperson,
        isSkCouncilor,
        isTanod,
        isBhw,
        isDaycareWorker,
        isStaff,
        isResident,
        isAudit,
        isPublic,
        isLoggedIn,
        isAdmin,
        isBarangayStaff,
        UserTypes,
        refreshRole: fetchRole,
        userStore,
    };
}
