package com.miya.fastcashier.net;


import com.miya.fastcashier.beans.SelfCashierAccountInfo;
import com.miya.fastcashier.service.AccountService;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 签名拦截器
 * 添加请求头校验 AUTHORIZATION
 */
public class RequestSignInterceptor implements Interceptor {

    private static final String AUTHORIZATION = "Authorization";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        String requestUrl = original.url().toString();

        Request.Builder requestBuilder = original.newBuilder();
        SelfCashierAccountInfo accountInfo = AccountService.INSTANCE.getAccountInfo();
        if (accountInfo != null && accountInfo.getAccessToken() != null) {
            String loginUrl = ApiService.Companion.wrapUrl(ApiService.LOGIN);
            if (!requestUrl.equals(loginUrl)) {
                requestBuilder.addHeader(AUTHORIZATION, "bearer " + accountInfo.getAccessToken().getAccessToken());
            }
        }
        Request request = requestBuilder.build();
        return chain.proceed(request);
    }
}
