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


import com.amazon.spapi.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class AuthorizationCodeExchange {

    private static final String TOKEN_ENDPOINT = "https://api.amazon.com/auth/o2/token";

    public static String exchangeAuthorizationCodeForRefreshToken(
            String clientId,
            String clientSecret,
            String authorizationCode,
            String redirectUri
    ) throws IOException, JSONException {
        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(null, new byte[0]);

        String url = TOKEN_ENDPOINT + "?" +
                "grant_type=authorization_code" +
                "&code=" + authorizationCode +
                "&client_id=" + clientId +
                "&client_secret=" + clientSecret +
                "&redirect_uri=" + redirectUri;

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();

        JSONObject jsonResponse = new JSONObject(responseBody);
        return jsonResponse.getString("refresh_token");
    }
}