package com.example.petstoremobile.api.auth;

import androidx.annotation.NonNull;

import java.io.IOException;

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

//Used to get the token from the backend for authenticated api calls
public class AuthInterceptor implements Interceptor {

    private final TokenManager tokenManager;

    public AuthInterceptor(TokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        String token = tokenManager.getToken();
        String url = chain.request().url().toString();

        if (url.contains("auth/login") || url.contains("auth/register")) {
            return chain.proceed(chain.request());
        }

        //If we have a token then add it to the request
        if (token != null) {
            Request request = chain.request().newBuilder()
                    .addHeader("Authorization", "Bearer " + token)
                    .build();
            return chain.proceed(request);
        }

        //If no token then just pass the request
        return chain.proceed(chain.request());
    }
}
