import { NextRequest, NextResponse } from "next/server";
import { bagistoFetch } from "@/utils/bagisto";
import { isBagistoError } from "@/utils/type-guards";
import { getAuthToken } from "@/utils/helper";
import {
    CREATE_ADD_PRODUCT_IN_CART,
    REMOVE_CART_ITEM,
    UPDATE_CART_ITEM,
    GET_CART_ITEM,
    CREATE_CART_TOKEN,
    CREATE_MERGE_CART,
    GET_CHECKOUT_ADDRESSES,
    GET_CHECKOUT_SHIPPING_RATES,
    GET_CHECKOUT_PAYMENT_METHODS,
    CREATE_CHECKOUT_ADDRESS,
    CREATE_CHECKOUT_SHIPPING_METHODS,
    CREATE_CHECKOUT_PAYMENT_METHODS,
    CREATE_CHECKOUT_ORDER,
    CREATE_PRODUCT_REVIEW,
    CREATE_PAYMENT_INITIATE,
    CREATE_SAVE_CHECKOUT_CART,
    GET_ORDER_DETAILS,
    CREATE_CANCEL_ORDER,
    // GET_PRODUCT_BY_URL_KEY,
} from "@/graphql";

const ALLOWED_OPERATIONS: Record<string, any> = {
    createAddProductInCart: CREATE_ADD_PRODUCT_IN_CART,
    RemoveCartItem: REMOVE_CART_ITEM,
    UpdateCartItem: UPDATE_CART_ITEM,
    GetCartItem: GET_CART_ITEM,
    CreateCart: CREATE_CART_TOKEN,
    createMergeCart: CREATE_MERGE_CART,
    collectionGetCheckoutAddresses: GET_CHECKOUT_ADDRESSES,
    CheckoutShippingRates: GET_CHECKOUT_SHIPPING_RATES,
    CheckoutPaymentMethods: GET_CHECKOUT_PAYMENT_METHODS,
    createCheckoutAddress: CREATE_CHECKOUT_ADDRESS,
    CreateCheckoutShippingMethod: CREATE_CHECKOUT_SHIPPING_METHODS,
    CreateCheckoutPaymentMethod: CREATE_CHECKOUT_PAYMENT_METHODS,
    CreateCheckoutOrder: CREATE_CHECKOUT_ORDER,
    CreateProductReview: CREATE_PRODUCT_REVIEW,
    CreatePaymentInitiate: CREATE_PAYMENT_INITIATE, // 创建订单
    CreateSaveCheckoutCart: CREATE_SAVE_CHECKOUT_CART,
    GetOrderDetails: GET_ORDER_DETAILS, // 获取订单详情
    CreateCancelOrder: CREATE_CANCEL_ORDER
};
// const QUERY_OPERATIONS: Record<string, any> = {
//     GetProductById: GET_PRODUCT_BY_URL_KEY,
// }

interface FetchOption  {
    query: string;
    variables?: Record<string, any>;
    cache?: RequestCache;
    guestToken?: string;
    operationName?: string;
}

// 需要authorization的operation
function authorizationOperations(body: Record<string, any>,req:NextRequest): FetchOption {
    const { operationName, variables } = body;
    const guestToken = getAuthToken(req);
    const query = ALLOWED_OPERATIONS[operationName];
    const finalVariables = variables;

    /*if (operationName === 'CheckoutPaymentMethods' || operationName === 'CheckoutShippingRates') {
        finalVariables = { ...variables };
    }

    if (operationName === 'CreateCheckoutPaymentMethod') {
        finalVariables = {
            ...variables,
            successUrl: variables?.successUrl ?? `payment/success`,
            failureUrl: variables?.failureUrl ?? `payment/failure`,
            cancelUrl: variables?.cancelUrl ?? `payment/cancel`
        };
    }*/

    /*if (operationName === 'createCheckoutAddress' && body.billingFirstName) {
        finalVariables = {
            billingFirstName: body.billingFirstName,
            billingLastName: body.billingLastName,
            billingEmail: body.billingEmail,
            billingAddress: body.billingAddress,
            billingCity: body.billingCity,
            billingCountry: body.billingCountry,
            billingState: body.billingState,
            billingPostcode: body.billingPostcode,
            billingPhoneNumber: body.billingPhoneNumber,
            billingCompanyName: body.billingCompanyName,
            useForShipping: body.useForShipping,
            ...(!body.useForShipping && {
                shippingFirstName: body.shippingFirstName,
                shippingLastName: body.shippingLastName,
                shippingEmail: body.billingEmail,
                shippingAddress: body.shippingAddress,
                shippingCity: body.shippingCity,
                shippingCountry: body.shippingCountry,
                shippingState: body.shippingState,
                shippingPostcode: body.shippingPostcode,
                shippingPhoneNumber: body.shippingPhoneNumber,
                shippingCompanyName: body.shippingCompanyName,
            })
        };
    }*/

    /*if (operationName === 'createAddProductInCart' && body.productId) {
        finalVariables = {
            cartId: body.cartId ?? null,
            productId: body.productId,
            quantity: body.quantity,
        };
    }*/
    return {
        query,
        variables: finalVariables,
        cache: "no-store",
        guestToken,
        operationName
    }
}


// 不需要authorization的operation
function notAuthorizationOperations(body: Record<string, any>): FetchOption {
    const { operationName, query: bodyGraphqlQuery, variables } = body;
    const query = bodyGraphqlQuery;
    return {
        query,
        variables,
        cache: "no-store",
        operationName
    }
}

export async function POST(req: NextRequest) {
    try {
        const body = await req.json();
        const { operationName } = body;

        if (!operationName) {
            return NextResponse.json(
                { message: "Invalid or unauthorized operation: " + (operationName || "missing") },
                { status: 400 }
            );
        }
        let fetchOption: FetchOption = notAuthorizationOperations(body);
        if(ALLOWED_OPERATIONS[operationName]) {
            fetchOption = authorizationOperations(body,req);
        }

        
        const response = await bagistoFetch<any>(fetchOption);
        // console.log('response ------ ', response);
        return NextResponse.json({
            data: response.body.data,
        });
    } catch (error) {
        if (isBagistoError(error)) {
            return NextResponse.json(
                {
                    data: null,
                    error: error.cause ?? error,
                },
                { status: 200 }
            );
        }

        return NextResponse.json(
            {
                message: "Network error",
                error: error instanceof Error ? error.message : error,
            },
            { status: 500 }
        );
    }
}
