package com.ttstd.controlled.network;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ttstd.controlled.BuildConfig;
import com.ttstd.controlled.network.UnauthorizedInterceptor;

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 实例。
 *
 * OkHttpClient 内部维护连接池与线程池，必须全局复用，切勿每次请求都新建。
 */
public final class RetrofitClient {

    private static volatile Retrofit retrofit;
    private static volatile DeviceApi deviceApi;
    private static volatile OkHttpClient okHttpClient;

    private RetrofitClient() {
    }

    public static OkHttpClient okHttp() {
        if (okHttpClient == null) {
            synchronized (RetrofitClient.class) {
                if (okHttpClient == null) {
                    OkHttpClient.Builder builder = new OkHttpClient.Builder()
                            .connectTimeout(15, TimeUnit.SECONDS)
                            .readTimeout(15, TimeUnit.SECONDS)
                            .writeTimeout(15, TimeUnit.SECONDS)
                            .retryOnConnectionFailure(true)
                            .addInterceptor(new UnauthorizedInterceptor());
                    if (BuildConfig.DEBUG) {
                        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
                        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
                        builder.addInterceptor(logging);
                    }
                    okHttpClient = builder.build();
                }
            }
        }
        return okHttpClient;
    }

    private static Retrofit retrofit() {
        if (retrofit == null) {
            synchronized (RetrofitClient.class) {
                if (retrofit == null) {
                    // 服务端字段为 camelCase，与实体字段一致，这里显式声明以免全局 Gson 配置影响。
                    Gson gson = new GsonBuilder()
                            .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
                            .create();
                    retrofit = new Retrofit.Builder()
                            .baseUrl(normalizeBaseUrl(BuildConfig.API_BASE))
                            .client(okHttp())
                            .addConverterFactory(GsonConverterFactory.create(gson))
                            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                            .build();
                }
            }
        }
        return retrofit;
    }

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

    /** Retrofit 要求 baseUrl 必须以 "/" 结尾。 */
    private static String normalizeBaseUrl(String base) {
        if (base == null || base.isEmpty()) {
            return "https://www.ttstd.com/";
        }
        return base.endsWith("/") ? base : base + "/";
    }
}
