import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { AuthReturnGateHome } from '@/features/auth/ui/AuthReturnGateHome';
import { PostAuthRedirect } from '@/features/auth/ui/PostAuthRedirect';
import { getMe } from '@/features/auth/api.server';
import { getMyProfile } from '@/features/settings/api.server';
import { homePathOf } from '@/features/settings/types';
import { LOGIN_NEXT_COOKIE } from '@/features/extension/constants';

/**
 * Post–Google-OAuth landing and signed-in entry.
 * Extension sign-in stores a next path: honor that before CRM onboarding or Home.
 */
export default async function HomePage() {
  try {
    const me = await getMe();
    const pendingNext = (await cookies()).get(LOGIN_NEXT_COOKIE)?.value;
    if (pendingNext) {
      return <PostAuthRedirect />;
    }
    if (!me.onboarding.completed) {
      redirect('/onboarding/role');
    }
    const profile = await getMyProfile().catch(() => null);
    redirect(homePathOf(profile?.preferences.defaultHomePage));
  } catch (error) {
    if (typeof error === 'object' && error && 'digest' in error) throw error;
    return <AuthReturnGateHome />;
  }
}
