// composables/useAuth.ts
import { computed, ref } from 'vue';
import type { SessionData as UserSession, LogoutResponse } from '~/types/auth';


const sessionData = ref<UserSession | null>(null);
const isLoggedIn = ref(false);
const isLoading = ref(false);

const clearLocalAuthStorage = () => {
  if (!process.client) return;

  localStorage.removeItem('accessToken');
  localStorage.removeItem('refreshToken');
  sessionStorage.clear();
};

export const useAuthSession = () => {
  const fetchUserSession = async () => {
    isLoading.value = true;

    try {
      const response = await $fetch<UserSession>('/api/auth/sessionUser', {
        method: 'GET',
      });

      sessionData.value = response;
      isLoggedIn.value = !!response;
    } catch {
      sessionData.value = null;
      isLoggedIn.value = false;
    } finally {
      isLoading.value = false;
    }
  };

  const logout = async (): Promise<void> => {
    try {
      await $fetch<LogoutResponse>('/api/auth/logout', {
        method: 'POST',
      });
    } finally {
      clearLocalAuthStorage();
      sessionData.value = null;
      isLoggedIn.value = false;
      await navigateTo('/auth/login?logout=success');
    }
  };

  const fullLogout = async (): Promise<void> => {
    try {
      const response = await $fetch<LogoutResponse>('/api/auth/logout', {
        method: 'POST',
      });

      clearLocalAuthStorage();
      sessionData.value = null;
      isLoggedIn.value = false;

      if (process.client && response?.success && response?.logoutUrl) {
        window.location.href = response.logoutUrl;
        return;
      }

      await navigateTo('/auth/login?logout=full');
    } catch {
      clearLocalAuthStorage();
      sessionData.value = null;
      isLoggedIn.value = false;
      await navigateTo('/auth/login?logout=full');
    }
  };

  const user = computed(() => sessionData.value?.user ?? null);
  const userRoles = computed(() => sessionData.value?.user?.role ?? []);

  return {
    isLoggedIn,
    isLoading,
    sessionData,
    user,
    userRoles,
    fetchUserSession,
    logout,
    fullLogout,
  };
};
