import React from 'react'
import { Metadata } from 'next'
import { redirect, notFound } from 'next/navigation'
import { Order } from '@/lib/types/order'
import { Merchant } from '@/lib/types/merchant'
import dynamic from 'next/dynamic'

const PaymentPage = dynamic(() => import('@/components/pages/payments'))

interface PageProps {
  params: Promise<{
    invoiceNumber: string
    username: string
  }>
}

export async function generateMetadata({
  params,
}: PageProps): Promise<Metadata> {
  const { username } = await params

  const [merchantRes] = await Promise.all([
    fetch(`${process.env.API_URL}/merchants/${username}`, {
      cache: 'no-store',
    }),
  ])

  if (!merchantRes.ok) {
    notFound()
  }

  const { data: merchant }: { data: Merchant } = await merchantRes.json()

  return {
    title: `${merchant.name} | Payment`,
  }
}

async function Page({ params }: PageProps) {
  const { invoiceNumber } = await params

  const res = await fetch(`${process.env.API_URL}/orders/${invoiceNumber}`, {
    cache: 'no-store',
  })

  const { data }: { data: Order } = await res.json()

  if (!data) {
    redirect('/404')
  }

  return <PaymentPage order={data} />
}

export default Page
