import {Suspense} from "react";
import { getServerSession } from "next-auth";
import { cookies } from 'next/headers';
import { redirect, RedirectType } from 'next/navigation'
import { authOptions } from "@utils/auth";
import {serverGraphqlFetch} from "@utils/bagisto/index";
import {GET_ORDER_DETAILS} from "@/graphql";
import { OrderDetailsData } from "@/types/customer/type";
import SuccessPageSkeleton from "../_components/SuccessPageSkeleton";
import SkeletonCancelOrFailure from "../_components/SkeletonCancelOrFailure";
import CancelOrFailure from "../_components/CancelOrFailure";
import OrderDetailWrapper from "../_components/OrderDetailWrapper";
import { GUEST_CART_TOKEN } from "@/utils/constants";

// 如果是游客：请求完订单详情后删除cookie里原来的carttoken cartid
export default async function SuccessPage({searchParams}: {
  searchParams?: Promise<{ [key: string]: string | string[] | undefined }>;
})  {
    const cookieStore = await cookies();
    // 登录用户cookie里没有GUEST_CART_ID
    if(!cookieStore.get(GUEST_CART_TOKEN)) {
        redirect('/', RedirectType.replace);
    }
    const session = await getServerSession(authOptions);// 游客是null
    const isGuest = session === null;
    
    const query = await searchParams; // awx_return_result
    const orderid = query?.orderId;
    const paymentResult = query?.awx_return_result ?? query?.return_result; // 支付状态


    if (!orderid) {
        redirect("/", RedirectType.replace);
    }



    const orderDetailPromise = serverGraphqlFetch<OrderDetailsData,{id:string}>({
        query: GET_ORDER_DETAILS,
        variables: {
            id:  orderid as string
        }
    });

    return (
        
        <div className="w-full">
            {paymentResult === 'success' && 
                <Suspense fallback={<SuccessPageSkeleton />}>
                    <OrderDetailWrapper orderDetailPromise={orderDetailPromise} 
                        isGuest={isGuest}
                    />
                </Suspense>

            }
            {(paymentResult === 'cancel' || paymentResult === 'failure') &&
                <Suspense fallback={<SkeletonCancelOrFailure/>}>
                    <CancelOrFailure isGuest={isGuest} orderDetailPromise={orderDetailPromise} paymentStatus={paymentResult} />
                </Suspense>
            }
            
        </div>
    );
}
