"use client";

import { GET_CHECKOUT_ADDRESSES, CREATE_CHECKOUT_ADDRESS } from "@/graphql";
import {useApolloClient} from "@apollo/client/react";
import { 
    CheckoutAddressNode,
    ShipAddressFormData,
    BillAddressFormData,
    CreateCheckoutAddressVariables
} from "@/types/checkout/type";
import {normalizePhoneForForm} from "@/utils/phoneNumberTools";
/**
 * 对比shipping address与billing address的数据是否完全相同
 */
export function addressIsSame(billAddress: BillAddressFormData | null, shipAddress: ShipAddressFormData | null) {
    if(billAddress === null && shipAddress === null) {
        return true;
    } else if(billAddress !== null && shipAddress !== null) {
        return (
           billAddress.billingEmail === shipAddress.shippingEmail &&
           billAddress.billingFirstName === shipAddress.shippingFirstName &&
           billAddress.billingLastName === shipAddress.shippingLastName &&
           billAddress.billingCompanyName === shipAddress.shippingCompanyName &&
           billAddress.billingAddress === shipAddress.shippingAddress &&
           billAddress.billingCity === shipAddress.shippingCity &&
           billAddress.billingState === shipAddress.shippingState &&
           billAddress.billingCountry === shipAddress.shippingCountry &&
           billAddress.billingPostcode === shipAddress.shippingPostcode &&
           billAddress.billingPhoneNumber === shipAddress.shippingPhoneNumber 
        );
    } else {
        return false;
    }
}


export function useCheckoutAddress(loginEmail: string) {
    const apolloClient = useApolloClient();


    const getCheckoutAddress = (
        resolveCallback: (shippingAddress:ShipAddressFormData, billingAddress: BillAddressFormData) => void = () => {}, 
        rejectCallback: () => void = ()=> {}
    ) => {
        return apolloClient.query({
            query: GET_CHECKOUT_ADDRESSES,
            fetchPolicy: "no-cache",
            context: {
                fetchOptions: {
                    cache: 'no-store',
                },
        
            }
        }).then((res) => {
            const address =  res.data?.collectionGetCheckoutAddresses?.edges?.map(
                    (edge: { node: CheckoutAddressNode }) => edge.node
                ) || [];
            const billAddress = address.find((a: CheckoutAddressNode) => a?.addressType === "cart_billing") || null;
            const shipAddress = address.find((a: CheckoutAddressNode) => a?.addressType === "cart_shipping") || null;
            const shipCountry = shipAddress?.country || "US";
            const billCountry = billAddress?.country || "US";

            const defaultBillAddress: BillAddressFormData = {
                billingAddressId: billAddress?._id || "",
                billingEmail: billAddress?.email ?? loginEmail ?? "",
                billingFirstName: billAddress?.firstName || "",
                billingLastName: billAddress?.lastName || "",
                billingCompanyName: billAddress?.companyName || "",
                billingAddress: billAddress?.address || "",
                billingCountry: billCountry,
                billingState: billAddress?.state || "",
                billingCity: billAddress?.city || "",
                billingPostcode: billAddress?.postcode || "",
                billingPhoneNumber: normalizePhoneForForm(billAddress?.phone, billCountry) || "",
                billingSameAsShipping: true, // 这个字段前端维护，不传给后端（bagisto是以billing address为准，但是运营要以shipping address为准，所以前端自己维护billing address与shipping address 同步）
            };

            const defaultShipAddress: ShipAddressFormData = {
                shippingAddressId: shipAddress?._id || "",
                shippingEmail: shipAddress?.email ?? loginEmail ?? "",
                shippingFirstName: shipAddress?.firstName || "",
                shippingLastName: shipAddress?.lastName || "",
                shippingCompanyName: shipAddress?.companyName || "",
                shippingAddress: shipAddress?.address || "",
                shippingCountry: shipCountry,
                shippingState: shipAddress?.state || "",
                shippingCity: shipAddress?.city || "",
                shippingPostcode: shipAddress?.postcode || "",
                shippingPhoneNumber: normalizePhoneForForm(shipAddress?.phone, shipCountry) || "",
            };

            const billSameAsShip = addressIsSame(defaultBillAddress, defaultShipAddress);
            defaultBillAddress.billingSameAsShipping = billSameAsShip;
            console.log('GET_CHECKOUT_ADDRESSES res ---- ',defaultShipAddress,defaultBillAddress);
            resolveCallback(defaultShipAddress,defaultBillAddress);
            return {
                shippingAddress: defaultShipAddress,
                billingAddress: defaultBillAddress
            }
        
        }).catch((err) => {
            console.error('GET_CHECKOUT_ADDRESSES error ---- ',err);
            rejectCallback();
            return null;
        });
    };

    const saveCheckoutAddress = (saveAddressParam: CreateCheckoutAddressVariables) => {
        return apolloClient.mutate({
            mutation: CREATE_CHECKOUT_ADDRESS,
            variables:saveAddressParam,
        });
    }

  return {
    getCheckoutAddress,
    saveCheckoutAddress,
  };
}



