package com.isidroid.test_utils

import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest

class MockWebServerWrapper(
    private val dispatchListener: DispatcherListener
) {
    private val mockWebServer = MockWebServer()

    fun create(): MockWebServer {
        mockWebServer.start(8080)
        mockWebServer.dispatcher = object : Dispatcher() {
            override fun dispatch(request: RecordedRequest): MockResponse {
                val bodyJson = request.body.inputStream().bufferedReader().use { it.readText() }

                val responseFile = buildString {
                    append(dispatchListener.convertUrlToLocalFile(request.path.orEmpty(), method = request.method, body = bodyJson))
                    append(".json")
                }


                println("${request.method}: path=${request.path}, response.file=$responseFile, ")
                return MockResponse().setResponseCode(200).setBody(getMockResponse(responseFile))
            }
        }

        return mockWebServer
    }

    fun interface DispatcherListener {
        fun convertUrlToLocalFile(path: String, method: String?, body: String?): String
    }
}