package com.ttstd.controller.network;

import com.ttstd.controller.BuildConfig;
import com.ttstd.controller.config.CommonConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit + OkHttp 单例。
 *
 * <p>统一注入 {@link AuthInterceptor} 携带 Bearer 令牌，并通过 RxJava3 适配器
 * 返回 {@code Single} 冷流，便于在 ViewModel 中配合 CompositeDisposable 管理生命周期。
 */
public final class RetrofitClient {
    /** 网络超时（秒）。 */
    public static final long TIMEOUT_SECONDS = 15L;

    private static volatile Retrofit retrofit;
    private static volatile AuthApi authApi;
    private static volatile ClientApi clientApi;

    private RetrofitClient() {
    }

    private static Retrofit retrofit() {
        if (retrofit == null) {
            synchronized (RetrofitClient.class) {
                if (retrofit == null) {
                    retrofit = build();
                }
            }
        }
        return retrofit;
    }

    private static Retrofit build() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .writeTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .addInterceptor(new AuthInterceptor())
                .addInterceptor(new UnauthorizedInterceptor())
                .addInterceptor(logging)
                .build();

        return new Retrofit.Builder()
                .baseUrl(BuildConfig.API_BASE)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();
    }

    public static AuthApi authApi() {
        if (authApi == null) {
            synchronized (RetrofitClient.class) {
                if (authApi == null) {
                    authApi = retrofit().create(AuthApi.class);
                }
            }
        }
        return authApi;
    }

    public static ClientApi clientApi() {
        if (clientApi == null) {
            synchronized (RetrofitClient.class) {
                if (clientApi == null) {
                    clientApi = retrofit().create(ClientApi.class);
                }
            }
        }
        return clientApi;
    }
}
