package com.jordanbot.autoride.api

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Body
import retrofit2.http.POST
import okhttp3.Interceptor
import okhttp3.OkHttpClient

// Data models for the API
data class RideLogRequest(
    val platform: String,
    val price: Double,
    val pickupDistance: String,
    val dropoffDistance: String,
    val timeToPickup: String,
    val pickupAddress: String,
    val dropoffAddress: String,
    val isAccepted: Boolean,
    val rawText: String,
    val fingerprint: String,
    val latitude: Double? = null,
    val longitude: Double? = null
)

data class LocationPoint(
    val latitude: Double,
    val longitude: Double,
    val speed: Float,
    val timestamp: Long
)

data class BulkLocationRequest(
    val fingerprint: String,
    val locations: List<LocationPoint>
)

data class ApiResponse(
    val success: Boolean,
    val message: String
)

data class CheckSubscriptionRequest(val fingerprint: String)
data class CheckSubscriptionResponse(
    val success: Boolean,
    val plan: String?,
    val expires_at: String?,
    val rides_today: Int?,
    val rides_limit: Int?,
    val can_accept: Boolean?
)

data class ActivateSubscriptionRequest(
    val fingerprint: String,
    val plan: String,
    val payment_ref: String?
)

data class ActivateSubscriptionResponse(
    val success: Boolean,
    val message: String?,
    val plan: String?,
    val expires_at: String?
)

interface BackendApiService {
    @POST("api/rides.php")
    suspend fun logRide(@Body request: RideLogRequest): ApiResponse

    @POST("api/location.php")
    suspend fun updateBulkLocation(@Body request: BulkLocationRequest): ApiResponse

    @POST("api/subscription/check.php")
    suspend fun checkSubscription(@Body request: CheckSubscriptionRequest): CheckSubscriptionResponse
    
    @POST("api/subscription/activate.php")
    suspend fun activateSubscription(@Body request: ActivateSubscriptionRequest): ActivateSubscriptionResponse
}

object ApiClient {
    // Replace with your actual server URL
    private const val BASE_URL = "https://lawer.tripz-egypt.com/jordan_bot/backend/"
    private val API_KEY = com.jordanbot.autoride.BuildConfig.API_KEY
    var appSignature: String = ""

    private val httpClient = OkHttpClient.Builder().apply {
        addInterceptor(Interceptor { chain ->
            val request = chain.request().newBuilder()
                .addHeader("X-API-Key", API_KEY)
                .addHeader("X-App-Signature", appSignature)
                .build()
            chain.proceed(request)
        })
    }.build()

    val service: BackendApiService by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(httpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(BackendApiService::class.java)
    }
}
