import type { Metadata } from 'next'
import { cookies } from 'next/headers'
import { getTranslations } from 'next-intl/server'
import { getSiteInfo } from '@/lib/db/queries/getSiteInfo'
import { CUSTOMER_SESSION_COOKIE, validateCustomerSession } from '@/lib/auth/customerSession'
import TrackOrderClient from '@/components/frontend/track-order/TrackOrderClient'

interface PageProps {
  params: Promise<{ locale: string }>
  searchParams: Promise<{ order?: string }>
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { locale } = await params
  const [t, siteInfo] = await Promise.all([
    getTranslations({ locale, namespace: 'TrackOrder' }),
    getSiteInfo(),
  ])
  return {
    title: `${t('metaTitle')} | ${siteInfo.siteName}`,
    description: t('metaDescription'),
  }
}

// /track-order?order=ORD-… is linked from the order confirmation page. A
// logged-in customer tracking their own order skips the email/phone step
// (the API checks ownership from the session cookie); everyone else gets the
// form with the order number pre-filled.
export default async function TrackOrderPage({ searchParams }: PageProps) {
  const { order } = await searchParams
  // Same shape check as the contact page's ?order= prefill — order numbers
  // look like ORD-20260918-34F64E; anything else is ignored.
  const initialOrderNumber = order && /^[A-Za-z0-9-]{3,50}$/.test(order) ? order : ''

  const sessionId = (await cookies()).get(CUSTOMER_SESSION_COOKIE)?.value
  const isLoggedIn = sessionId ? !!(await validateCustomerSession(sessionId)) : false

  return <TrackOrderClient initialOrderNumber={initialOrderNumber} isLoggedIn={isLoggedIn} />
}
