import { redirect } from 'next/navigation';

import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
import { retrieveOrder } from '@lib/data/orders';

import { pathsConfig } from '@kit/shared/config';

import { withI18n } from '~/lib/i18n/with-i18n';
import { getAnalysisOrder } from '~/lib/services/order.service';

import OrderConfirmedLoadingWrapper from './order-confirmed-loading-wrapper';

export async function generateMetadata() {
  const { t } = await createI18nServerInstance();

  return {
    title: t('cart:orderConfirmed.title'),
  };
}

async function OrderConfirmedPage(props: {
  params: Promise<{ orderId: string }>;
}) {
  const params = await props.params;

  const order = await getAnalysisOrder({
    analysisOrderId: Number(params.orderId),
  }).catch(() => null);
  if (!order) {
    redirect(pathsConfig.app.myOrders);
  }

  const medusaOrder = await retrieveOrder(order.medusa_order_id).catch(
    () => null,
  );
  if (!medusaOrder) {
    redirect(pathsConfig.app.myOrders);
  }

  return (
    <OrderConfirmedLoadingWrapper medusaOrder={medusaOrder} order={order} />
  );
}

export default withI18n(OrderConfirmedPage);
