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 NotificationApi(private val client: HttpClient = ApiClient.httpClient) {
    private val baseUrl = ApiClient.getBaseUrl()

    /**
     * Register a device for push notifications
     */
    suspend fun registerDevice(
        token: String,
        request: DeviceRegistrationRequest
    ): ApiResult<DeviceRegistrationResponse> {
        return try {
            val response = client.post("$baseUrl/notifications/devices/register/") {
                header("Authorization", "Token $token")
                contentType(ContentType.Application.Json)
                setBody(request)
            }

            if (response.status.isSuccess()) {
                ApiResult.Success(response.body())
            } else {
                val errorBody = try {
                    response.body<Map<String, String>>()
                } catch (e: Exception) {
                    mapOf("error" to "Device registration failed")
                }
                ApiResult.Error(errorBody["error"] ?: "Device registration failed", response.status.value)
            }
        } catch (e: Exception) {
            ApiResult.Error(e.message ?: "Unknown error occurred")
        }
    }

    suspend fun unregisterDevice(
        token: String,
        deviceId: Int
    ): ApiResult<Unit> {
        return try {
            val response = client.delete("$baseUrl/notifications/devices/$deviceId/") {
                header("Authorization", "Token $token")
            }

            if (response.status.isSuccess()) {
                ApiResult.Success(Unit)
            } else {
                ApiResult.Error("Device unregistration failed", response.status.value)
            }
        } catch (e: Exception) {
            ApiResult.Error(e.message ?: "Unknown error occurred")
        }
    }

    /**
     * Get user's notification preferences
     */
    suspend fun getNotificationPreferences(token: String): ApiResult<NotificationPreference> {
        return try {
            val response = client.get("$baseUrl/notifications/preferences/") {
                header("Authorization", "Token $token")
            }

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

    /**
     * Update notification preferences
     */
    suspend fun updateNotificationPreferences(
        token: String,
        request: UpdateNotificationPreferencesRequest
    ): ApiResult<NotificationPreference> {
        return try {
            val response = client.put("$baseUrl/notifications/preferences/") {
                header("Authorization", "Token $token")
                contentType(ContentType.Application.Json)
                setBody(request)
            }

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

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

            if (response.status.isSuccess()) {
                val listResponse: NotificationListResponse = response.body()
                ApiResult.Success(listResponse.results)
            } else {
                ApiResult.Error("Failed to get notification history", response.status.value)
            }
        } catch (e: Exception) {
            ApiResult.Error(e.message ?: "Unknown error occurred")
        }
    }

    suspend fun markNotificationAsRead(
        token: String,
        notificationId: Int
    ): ApiResult<MessageResponse> {
        return try {
            val response = client.post("$baseUrl/notifications/$notificationId/read/") {
                header("Authorization", "Token $token")
            }

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

    suspend fun markAllNotificationsAsRead(token: String): ApiResult<MessageResponse> {
        return try {
            val response = client.post("$baseUrl/notifications/mark-all-read/") {
                header("Authorization", "Token $token")
            }

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

    suspend fun getUnreadCount(token: String): ApiResult<UnreadCountResponse> {
        return try {
            val response = client.get("$baseUrl/notifications/unread-count/") {
                header("Authorization", "Token $token")
            }

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