// utils/api/verifyFromFunction.ts

const VERIFY_URL = 'https://verifysession-edvvp3hbnq-du.a.run.app';

export type VerifiedSession = {
  uid: string;
  email: string;
  role: number;
};

export async function verifySession(): Promise<VerifiedSession> {
  console.log('verifySession (client): Initiating GET request to', VERIFY_URL); // Log start

  try {
    // We use $fetchRaw here to inspect the full response, including headers
    const response = await $fetch.raw<VerifiedSession>(VERIFY_URL, {
      method: 'GET',
      credentials: 'include', // ensures session cookie is sent
    });

    console.log('verifySession (client): Response status:', response.status);
    console.log('verifySession (client): Response headers:', response.headers); // Log all response headers

    // To check if a specific cookie was sent by the browser in the *request* (not response):
    // This is hard to do directly with $fetch on the client-side *before* the request is sent,
    // you'd typically use the Network tab for that.

    // If you need the response body:
    const data = await response._data;
    console.log('verifySession (client): Response data:', data);

    if (response.status === 200 && data) {
      console.log('verifySession (client): Session verification successful.');
      return data;
    } else {
      const errorMessage = `verifySession (client): Verification failed with status ${response.status}`;
      console.error(errorMessage);
      throw new Error(errorMessage);
    }
  } catch (error) {
    console.error('verifySession (client): Error during verification:', error);
    // Re-throw the error so it can be caught by the calling code
    throw error;
  }
}
