package com.hys.app.service.otherService.amazon;

import com.amazon.spapi.api.ListingsApi;
import com.amazon.spapi.client.ApiException;
import com.amazon.spapi.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import com.amazon.spapi.SellingPartnerAPIAA.AWSAuthenticationCredentials;
import com.amazon.spapi.SellingPartnerAPIAA.AWSAuthenticationCredentialsProvider;
import com.amazon.spapi.model.listingsitems.ListingsItemPatchRequest;
import com.amazon.spapi.model.listingsitems.PatchOperation;

import java.util.*;

public class AmazonProductUpdater {

    private final ListingsApi listingsApi;
    private final String sellerId;
    private final List<String> marketplaceIds;

    public AmazonProductUpdater(String sellerId, List<String> marketplaceIds) {
        this.sellerId = sellerId;
        this.marketplaceIds = marketplaceIds;
        this.listingsApi = initializeListingsApi();
    }

    private ListingsApi initializeListingsApi() {
        // 设置 LWA 凭证
        LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                .clientId("YOUR_LWA_CLIENT_ID")
                .clientSecret("YOUR_LWA_CLIENT_SECRET")
                .refreshToken("YOUR_REFRESH_TOKEN")
                .endpoint("https://api.amazon.com/auth/o2/token")
                .build();

        // 设置 AWS 凭证
        AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                .accessKeyId("YOUR_AWS_ACCESS_KEY")
                .secretKey("YOUR_AWS_SECRET_KEY")
                .region("YOUR_AWS_REGION")
                .build();

        AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                .roleArn("YOUR_ROLE_ARN")
                .roleSessionName("session-name")
                .build();

        // 初始化并返回 ListingsApi
        return new ListingsApi.Builder()
                .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                .awsAuthenticationCredentials(awsAuthenticationCredentials)
                .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                .endpoint("https://sellingpartnerapi-na.amazon.com")  // 根据您的区域选择正确的端点
                .build();
    }

    public void updateProduct(String sku, Map<String, Object> updatedAttributes) {
        try {
            List<PatchOperation> patchOperations = new ArrayList<>();

            // 为每个更新的属性创建一个 PatchOperation
            for (Map.Entry<String, Object> entry : updatedAttributes.entrySet()) {
                patchOperations.add(new PatchOperation()
                        .op(PatchOperation.OpEnum.REPLACE)
                        .path("attributes/" + entry.getKey())
                        .value(new ArrayList<>()));
            }

            ListingsItemPatchRequest patchRequest = new ListingsItemPatchRequest()
                    .productType("PRODUCT_TYPE")  // 根据实际产品类型设置
                    .patches(patchOperations);

            // 调用 API 更新商品
            listingsApi.patchListingsItem(sellerId, sku, marketplaceIds, patchRequest, "PATCH_LISTINGS_ITEM");

            System.out.println("Product " + sku + " updated successfully on Amazon!");
        } catch (ApiException e) {
            System.err.println("Error updating product " + sku + " on Amazon: " + e.getMessage());
            System.err.println("Response body: " + e.getResponseBody());
            e.printStackTrace();
        }
    }

    // 示例使用方法
    public static void main(String[] args) {
        String sellerId = "YOUR_SELLER_ID";
        List<String> marketplaceIds = Arrays.asList("YOUR_MARKETPLACE_ID");
        AmazonProductUpdater updater = new AmazonProductUpdater(sellerId, marketplaceIds);

        // 假设这是从您的后台系统获取的更新信息
        String skuToUpdate = "YOUR_PRODUCT_SKU";
        Map<String, Object> updatedAttributes = new HashMap<>();
        updatedAttributes.put("title", "Updated Product Title");
        updatedAttributes.put("brand", "Updated Brand");
        updatedAttributes.put("bullet_point", Arrays.asList("New feature 1", "New feature 2"));
        updatedAttributes.put("list_price", 29.99);

        updater.updateProduct(skuToUpdate, updatedAttributes);
    }
}