package com.tt.honeyDue.network

import com.tt.honeyDue.models.*
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*

class SubscriptionApi(private val client: HttpClient = ApiClient.httpClient) {
    private val baseUrl = ApiClient.getBaseUrl()

    suspend fun getSubscriptionStatus(token: String): ApiResult<SubscriptionStatus> {
        return try {
            val response = client.get("$baseUrl/subscription/status/") {
                header("Authorization", "Token $token")
            }

            if (response.status.isSuccess()) {
                ApiResult.Success(response.body())
            } else {
                ApiResult.Error("Failed to fetch subscription status", response.status.value)
            }
        } catch (e: Exception) {
            ApiResult.Error(e.message ?: "Unknown error occurred")
        }
    }

    suspend fun getUpgradeTriggers(token: String? = null): ApiResult<Map<String, UpgradeTriggerData>> {
        return try {
            val response = client.get("$baseUrl/subscription/upgrade-triggers/") {
                // Token is optional - endpoint is public
                token?.let { header("Authorization", "Token $it") }
            }

            if (response.status.isSuccess()) {
                ApiResult.Success(response.body())
            } else {
                ApiResult.Error("Failed to fetch upgrade triggers", response.status.value)
            }
        } catch (e: Exception) {
            ApiResult.Error(e.message ?: "Unknown error occurred")
        }
    }

    suspend fun getFeatureBenefits(token: String): ApiResult<List<FeatureBenefit>> {
        return try {
            val response = client.get("$baseUrl/subscription/features/") {
                header("Authorization", "Token $token")
            }

            if (response.status.isSuccess()) {
                ApiResult.Success(response.body())
            } else {
                ApiResult.Error("Failed to fetch feature benefits", response.status.value)
            }
        } catch (e: Exception) {
            ApiResult.Error(e.message ?: "Unknown error occurred")
        }
    }

    suspend fun getActivePromotions(token: String): ApiResult<List<Promotion>> {
        return try {
            val response = client.get("$baseUrl/subscription/promotions/") {
                header("Authorization", "Token $token")
            }

            if (response.status.isSuccess()) {
                ApiResult.Success(response.body())
            } else {
                ApiResult.Error("Failed to fetch promotions", response.status.value)
            }
        } catch (e: Exception) {
            ApiResult.Error(e.message ?: "Unknown error occurred")
        }
    }

    /**
     * Verify/process iOS purchase with backend
     * Used for both new purchases and restore
     */
    suspend fun verifyIOSReceipt(
        token: String,
        receiptData: String,
        transactionId: String
    ): ApiResult<VerificationResponse> {
        return try {
            val response = client.post("$baseUrl/subscription/purchase/") {
                header("Authorization", "Token $token")
                contentType(ContentType.Application.Json)
                setBody(mapOf(
                    "platform" to "ios",
                    "receipt_data" to receiptData,
                    "transaction_id" to transactionId
                ))
            }

            if (response.status.isSuccess()) {
                ApiResult.Success(response.body())
            } else {
                ApiResult.Error("Failed to verify iOS receipt", response.status.value)
            }
        } catch (e: Exception) {
            ApiResult.Error(e.message ?: "Unknown error occurred")
        }
    }

    /**
     * Verify/process Android purchase with backend
     * Used for both new purchases and restore
     */
    suspend fun verifyAndroidPurchase(
        token: String,
        purchaseToken: String,
        productId: String
    ): ApiResult<VerificationResponse> {
        return try {
            val response = client.post("$baseUrl/subscription/purchase/") {
                header("Authorization", "Token $token")
                contentType(ContentType.Application.Json)
                setBody(mapOf(
                    "platform" to "android",
                    "purchase_token" to purchaseToken,
                    "product_id" to productId
                ))
            }

            if (response.status.isSuccess()) {
                ApiResult.Success(response.body())
            } else {
                ApiResult.Error("Failed to verify Android purchase", response.status.value)
            }
        } catch (e: Exception) {
            ApiResult.Error(e.message ?: "Unknown error occurred")
        }
    }

    /**
     * Restore subscription from iOS/Android receipt
     */
    suspend fun restoreSubscription(
        token: String,
        platform: String,
        receiptData: String? = null,
        purchaseToken: String? = null,
        productId: String? = null
    ): ApiResult<VerificationResponse> {
        return try {
            val body = mutableMapOf<String, String>("platform" to platform)
            if (platform == "ios" && receiptData != null) {
                body["receipt_data"] = receiptData
            } else if (platform == "android" && purchaseToken != null) {
                body["purchase_token"] = purchaseToken
                productId?.let { body["product_id"] = it }
            }

            val response = client.post("$baseUrl/subscription/restore/") {
                header("Authorization", "Token $token")
                contentType(ContentType.Application.Json)
                setBody(body)
            }

            if (response.status.isSuccess()) {
                ApiResult.Success(response.body())
            } else {
                ApiResult.Error("Failed to restore subscription", response.status.value)
            }
        } catch (e: Exception) {
            ApiResult.Error(e.message ?: "Unknown error occurred")
        }
    }
}
