import { redirect } from 'next/navigation';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { logger } from '@/lib/logger';
import RegistrationLogoBar from '../components/RegistrationLogoBar';
import TermsContent from './TermsContent';
import '@/app/styles/registration-theme.css';

// Valid plans and intervals - same as checkout route
const VALID_PLANS = ['starter', 'growth', 'enhanced', 'professional'] as const;
const VALID_INTERVALS = ['monthly', 'annual'] as const;
type PlanName = (typeof VALID_PLANS)[number];
type BillingInterval = (typeof VALID_INTERVALS)[number];

interface PageProps {
  searchParams: Promise<{
    plan?: string;
    interval?: string;
  }>;
}

/**
 * Registration Terms Page
 *
 * Shows legal terms and conditions that users must agree to before
 * proceeding to Stripe checkout.
 *
 * Protection:
 * - Requires authentication (redirects to /terms/ if not signed in)
 * - Redirects to /dashboard if user already has a dealer (shouldn't be in registration flow)
 * - Requires valid plan parameter (redirects to /landing if invalid)
 */
export default async function RegistrationTerms(props: PageProps) {
  const searchParams = await props.searchParams;
  const plan = searchParams.plan;
  const intervalParam = searchParams.interval;

  // Validate interval - default to 'annual' if not provided or invalid
  const interval: BillingInterval = VALID_INTERVALS.includes(intervalParam as BillingInterval)
    ? (intervalParam as BillingInterval)
    : 'annual';

  // Diagnostic logging for billing interval bug investigation (Issue #336)
  logger.info(
    {
      plan,
      intervalParam,
      interval,
      rawSearchParams: JSON.stringify(searchParams),
    },
    '[Terms] Page loaded with billing parameters'
  );

  // Check authentication - unauthenticated users go to public terms page
  const session = await getServerSession(authOptions);
  if (!session?.user?.id) {
    redirect('/terms/');
  }

  // Check if user already has a dealer record
  // If they do, they shouldn't be in the registration flow at all
  // This catches the case where a dealer signs in via OAuth callback
  // that was set before the checkout endpoint's dealer guard could run
  const existingDealer = await prisma.dealer.findUnique({
    where: { userId: session.user.id },
    select: { id: true },
  });

  if (existingDealer) {
    redirect('/dashboard/');
  }

  // Validate plan parameter - only users in registration flow need this
  if (!plan || !VALID_PLANS.includes(plan as PlanName)) {
    redirect('/');
  }

  return (
    <div className="terms-page-root">
      {/* Logo Bar - Shared Component */}
      <RegistrationLogoBar />

      {/* Main Content */}
      <TermsContent plan={plan} interval={interval} />
    </div>
  );
}
