package ru.forbion.f7cloud.core.network

import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test

/** Централизованная обработка 401: interceptor бросает UnauthorizedException вместо ручных проверок. */
class UnauthorizedInterceptorTest {
    private lateinit var server: MockWebServer

    @Before fun setUp() { server = MockWebServer().apply { start() } }
    @After fun tearDown() { server.shutdown() }

    private fun call(client: OkHttpClient) =
        client.newCall(Request.Builder().url(server.url("/x")).build()).execute()

    @Test(expected = UnauthorizedException::class)
    fun `401 бросает UnauthorizedException`() {
        server.enqueue(MockResponse().setResponseCode(401))
        val client = OkHttpClient.Builder().addInterceptor(UnauthorizedInterceptor).build()
        call(client)
    }

    @Test fun `не-401 проходит как обычно`() {
        server.enqueue(MockResponse().setResponseCode(200).setBody("ok"))
        val client = OkHttpClient.Builder().addInterceptor(UnauthorizedInterceptor).build()
        call(client).use { assertEquals(200, it.code) }
    }

    @Test fun `403 не трактуется как Unauthorized`() {
        server.enqueue(MockResponse().setResponseCode(403))
        val client = OkHttpClient.Builder().addInterceptor(UnauthorizedInterceptor).build()
        call(client).use { assertEquals(403, it.code) }
    }
}
