"use client";

import { SessionProvider as NextAuthSessionProvider, useSession } from "next-auth/react";
import { useEffect, useRef } from "react";

// Component that syncs tokens from NextAuth session to localStorage
function TokenSync() {
  const { data: session, status } = useSession();
  const hasInitialized = useRef(false);

  useEffect(() => {
    if (status === "authenticated" && session?.user) {
      const user = session.user as { accessToken?: string; refreshToken?: string };

      // Only sync tokens from NextAuth to localStorage if:
      // 1. This is the first time we're initializing (fresh login)
      // 2. OR localStorage doesn't have tokens yet
      // This prevents overwriting tokens that were refreshed by the API interceptor
      const existingAccessToken = localStorage.getItem("accessToken");
      const existingRefreshToken = localStorage.getItem("refreshToken");

      // If localStorage is empty, this is likely a fresh login - sync tokens
      if (!existingAccessToken && !existingRefreshToken) {
        if (user.accessToken) {
          localStorage.setItem("accessToken", user.accessToken);
        }
        if (user.refreshToken) {
          localStorage.setItem("refreshToken", user.refreshToken);
        }
        hasInitialized.current = true;
      }
      // If we have tokens in localStorage but haven't initialized yet,
      // it means the API interceptor has refreshed tokens - don't overwrite
      else if (!hasInitialized.current) {
        hasInitialized.current = true;
      }
    } else if (status === "unauthenticated") {
      // Clear tokens when logged out
      localStorage.removeItem("accessToken");
      localStorage.removeItem("refreshToken");
      hasInitialized.current = false;
    }
  }, [session, status]);

  return null;
}

export function SessionProvider({ children }: { children: React.ReactNode }) {
  return (
    <NextAuthSessionProvider>
      <TokenSync />
      {children}
    </NextAuthSessionProvider>
  );
}
