import { redirect } from 'next/navigation';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import EditorForm from './EditorForm';

/**
 * Basic Dealer Editor Page
 *
 * Server component that fetches dealer data and renders the editor form.
 * Only accessible to authenticated dealers with an active account.
 */
export default async function DealerEditorPage() {
  // Step 1: Verify authentication
  const session = await getServerSession(authOptions);

  if (!session?.user?.id) {
    redirect('/api/auth/signin?callbackUrl=/dashboard/editor');
  }

  // Step 2: Fetch dealer data
  const dealer = await prisma.dealer.findFirst({
    where: { userId: session.user.id },
    include: { user: true },
  });

  // Step 3: Handle missing dealer
  if (!dealer) {
    // If no dealer found, redirect to pricing page to start subscription
    redirect('/');
  }

  // Step 4: Prepare initial form data
  const initialData = {
    dealerId: dealer.id,
    subdomain: dealer.subdomain || 'not-set',
    domainPrefix: dealer.domainPrefix,
    domain: dealer.domain,
    customDomain: dealer.customDomain,
    subscriptionTier: dealer.subscriptionTier,
    dealerNumber: dealer.dealerNumber,
    businessName: dealer.businessName,
    contactName: dealer.contactName,
    address: dealer.address,
    city: dealer.city,
    state: dealer.state,
    zip: dealer.zip,
    country: dealer.country,
    phone: dealer.phone,
    contactEmail: dealer.contactEmail,
    description: dealer.description,
    hideAddress: dealer.hideAddress,
    showContactName: dealer.showContactName,
    logoUrl: dealer.logoUrl,
    headScripts: dealer.headScripts,
    bodyScripts: dealer.bodyScripts,
    socialLinks: dealer.socialLinks as {
      facebook?: string;
      pinterest?: string;
      instagram?: string;
      youtube?: string;
      twitter?: string;
      x?: string;
    } | null,
    preferredLanguage: (dealer.preferredLanguage as 'en' | 'es' | 'fr') || 'en',
    allowLanguageSwitch: dealer.allowLanguageSwitch,
    amsoilLinkDomain:
      dealer.amsoilLinkDomain === 'com' || dealer.amsoilLinkDomain === 'ca'
        ? (dealer.amsoilLinkDomain as 'com' | 'ca')
        : null,
  };

  // Step 5: Render form with pre-filled data
  return <EditorForm initialData={initialData} />;
}
