import { User } from '@/types/auth';
import { extractCurrentUserV1, getCurrentUserV1 } from '@/services/v1/authAdapter';
import { normalizeAuthUser } from '@/lib/auth/normalize-user';
import { UserMetaCardSection } from './sections/metacard';
import UserEditableSection from '@/modules/profileModule/sections/userEditable';
import SecuritySettings from '@/modules/profileModule/components/SecuritySettings';
import ProfileOnboardingPrompt from '@/modules/profileModule/components/ProfileOnboardingPrompt';
import { shouldPromptForProfileOnboarding } from '@/lib/profileOnboardingPrompt';
import { redirect } from 'next/navigation';
import { getServerAuthData } from '@/lib/server-auth';

export const ProfileModule = async () => {
  let user: User | null = null;

  // Get auth data with automatic refresh handling
  // This will handle token refresh if access_token is missing but refresh_token exists
  const authData = await getServerAuthData();
  if (!authData) {
    return redirect('/signin');
  }

  try {
    const response = await getCurrentUserV1(authData.accessToken);
    user = normalizeAuthUser(extractCurrentUserV1(response));
  } catch (error) {
    console.warn('Warning: Failed to fetch user profile data:', error);
  }
  return (
    <div className="mx-auto w-full max-w-4xl px-4 sm:px-6">
      <div className="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03] lg:p-6">
        <h3 className="mb-5 text-lg font-semibold text-gray-800 dark:text-white/90 lg:mb-7">
          Profile
        </h3>
        {user && shouldPromptForProfileOnboarding(user) && <ProfileOnboardingPrompt />}
        <div className="space-y-6">
          <UserMetaCardSection initialProfile={user} />
          <UserEditableSection initialProfile={user} />
          {user && <SecuritySettings userId={user.id} />}
        </div>
      </div>
    </div>
  );
};
