package com.zyzf.coffeepreorder.api

import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import com.zyzf.coffeepreorder.api.model.CoffeeRemote
import com.zyzf.coffeepreorder.api.model.UserRemote
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.Path
import retrofit2.http.Query

interface MyServerService {
    @GET("user/")
    suspend fun getUsers(
        @Query("pageNo") page: Int,
        @Query("pageSize") limit: Int,
    ): List<UserRemote>

    @GET("user/{id}")
    suspend fun getUser(
        @Path("id") id: Int,
    ): UserRemote

    @GET("user/tryLogin")
    suspend fun tryLogin(
        @Query("login") login: String,
        @Query("password") password: String
    ): UserRemote

    @POST("user/")
    suspend fun createUser(
        @Body user: UserRemote,
    ): UserRemote

    @PUT("user/{id}")
    suspend fun updateUser(
        @Path("id") id: Int,
        @Body user: UserRemote,
    ): UserRemote

    @DELETE("user/{id}")
    suspend fun deleteUser(
        @Path("id") id: Int,
    ): UserRemote

    @GET("coffee/")
    suspend fun getCoffees(
        @Query("pageNo") page: Int,
        @Query("pageSize") limit: Int,
    ): List<CoffeeRemote>

    @GET("coffee/{id}")
    suspend fun getCoffee(
        @Path("id") id: Int,
    ): CoffeeRemote

    @POST("coffee/")
    suspend fun createCoffee(
        @Body coffee: CoffeeRemote,
    ): CoffeeRemote

    @PUT("coffee/{id}")
    suspend fun updateCoffee(
        @Path("id") id: Int,
        @Body coffee: CoffeeRemote,
    ): CoffeeRemote

    @DELETE("coffee/{id}")
    suspend fun deleteCoffee(
        @Path("id") id: Int,
    ): CoffeeRemote

    companion object {
        private const val BASE_URL = "http://192.168.0.100:8080/api/"

        @Volatile
        private var INSTANCE: MyServerService? = null

        fun getInstance(): MyServerService {
            return INSTANCE ?: synchronized(this) {
                val logger = HttpLoggingInterceptor()
                logger.level = HttpLoggingInterceptor.Level.BASIC
                val client = OkHttpClient.Builder()
                    .addInterceptor(logger)
                    .build()
                return Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
                    .build()
                    .create(MyServerService::class.java)
                    .also { INSTANCE = it }
            }
        }
    }
}