import { ref } from 'vue';
import api from '~/utils/api';
import type { AuthInfoResponse } from '~/types/auth';

const authInfo = ref<AuthInfoResponse | null>(null);
const isLoading = ref(false);
const errorMessage = ref<string | null>(null);

export const useAuthInfo = () => {
  const fetchAuthInfo = async (accessToken: string) => {
    if (!accessToken || !accessToken.trim()) {
      throw new Error('accessToken is required');
    }

    isLoading.value = true;
    errorMessage.value = null;

    try {
      const response = await api.get<AuthInfoResponse>('/api/v1/auth/info', {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${accessToken}`,
        },
      });

      authInfo.value = response.data;
      return response.data;
    } catch (error) {
      authInfo.value = null;
      errorMessage.value = error instanceof Error ? error.message : 'Failed to fetch auth info';
      throw error;
    } finally {
      isLoading.value = false;
    }
  };

  const clearAuthInfo = () => {
    authInfo.value = null;
    errorMessage.value = null;
  };

  return {
    authInfo,
    isLoading,
    errorMessage,
    fetchAuthInfo,
    clearAuthInfo,
  };
};
