'use client';
/**前端客户端组件调rest api 接口 */
import { getSession } from "next-auth/react";
import { getCartToken } from "@/utils/getCartToken";
import { BagistoSession } from "@/types/types";


let sessionCache: { session: BagistoSession | null; timestamp: number } | null = null;
const SESSION_CACHE_TTL = 5000;

async function getCachedSession(): Promise<BagistoSession | null> {

  const now = Date.now();

  if (sessionCache && now - sessionCache.timestamp < SESSION_CACHE_TTL) {
    return sessionCache.session;
  }
  //When called, getSession() will send a request to /api/auth/session and returns a promise with a session object, or null if no session exists.
  const session = (await getSession()) as BagistoSession | null;
  sessionCache = { session, timestamp: now };
  return session;
}

export async function clientFetch(apiUrl: string, options: RequestInit = {}) {
    // 请求的是nextjs的代理接口

    const session = await getCachedSession();
    const userToken = session?.user?.accessToken;
    const guestToken = !userToken ? getCartToken() : null;
    const token = userToken || guestToken;

    const headers = {
        ...(token && { Authorization: `Bearer ${token}` }),
        "Content-Type": "application/json",
    };
    if(options.headers) {
        options.headers = Object.assign(headers, options.headers);
    } else {
        options.headers = headers;
    }
    
    const response = await fetch(apiUrl, options);
    // console.log('response -- ', response);
    if(response.ok) {
        const result = await response.json();
        return result;
    } else {
        return {
            status: response.status,
            statusText: response.statusText,
            data: await response.text(),
        }
    }
    
}
