package com.ttstd.controller.network;

import androidx.annotation.NonNull;

import com.ttstd.controller.utils.TokenStore;

import java.io.IOException;

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

/**
 * 统一注入 Bearer 令牌的拦截器。
 *
 * <p>登录与刷新接口本身不需要（也不能）携带旧令牌，因此在此跳过。
 */
public class AuthInterceptor implements Interceptor {

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

        if (path.contains("/api/auth/login") || path.contains("/api/auth/refresh")) {
            return chain.proceed(original);
        }

        String token = TokenStore.get().getAccessToken();
        if (token == null || token.isEmpty()) {
            return chain.proceed(original);
        }

        Request authorized = original.newBuilder()
                .header("Authorization", "Bearer " + token)
                .build();
        return chain.proceed(authorized);
    }
}
