package com.jiooption.trading.network

import com.jiooption.trading.security.SecureStorage
import okhttp3.Interceptor
import okhttp3.Response

/**
 * OkHttp interceptor that attaches session cookies to all API requests
 * and saves session cookies from responses
 */
class AuthInterceptor(private val secureStorage: SecureStorage) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()

        // Add session cookie to request
        val sessionCookie = secureStorage.getSessionCookie()
        val requestBuilder = originalRequest.newBuilder()
            .header("Accept", "application/json")
            .header("X-Requested-With", "XMLHttpRequest")
            .header("X-App-Platform", "android")

        if (sessionCookie.isNotEmpty()) {
            requestBuilder.header("Cookie", sessionCookie)
        }

        val request = requestBuilder.build()
        val response = chain.proceed(request)

        // Save session cookie from response
        val cookies = response.headers("Set-Cookie")
        if (cookies.isNotEmpty()) {
            val cookieString = cookies.joinToString("; ") { cookie ->
                cookie.split(";").first()
            }
            if (cookieString.contains("PHPSESSID")) {
                secureStorage.saveSessionCookie(cookieString)
            }
        }

        return response
    }
}
