package com.tt.honeyDue.network

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

/**
 * API client for task templates.
 * Task templates are public (no auth required) and used for autocomplete when adding tasks.
 */
class TaskTemplateApi(private val client: HttpClient = ApiClient.httpClient) {
    private val baseUrl = ApiClient.getBaseUrl()

    /**
     * Get all task templates as a flat list
     */
    suspend fun getTemplates(): ApiResult<List<TaskTemplate>> {
        return try {
            val response = client.get("$baseUrl/tasks/templates/")

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

    /**
     * Get all task templates grouped by category
     */
    suspend fun getTemplatesGrouped(): ApiResult<TaskTemplatesGroupedResponse> {
        return try {
            val response = client.get("$baseUrl/tasks/templates/grouped/")

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

    /**
     * Search task templates by query string
     */
    suspend fun searchTemplates(query: String): ApiResult<List<TaskTemplate>> {
        return try {
            val response = client.get("$baseUrl/tasks/templates/search/") {
                parameter("q", query)
            }

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

    /**
     * Get templates by category ID
     */
    suspend fun getTemplatesByCategory(categoryId: Int): ApiResult<List<TaskTemplate>> {
        return try {
            val response = client.get("$baseUrl/tasks/templates/by-category/$categoryId/")

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

    /**
     * Get personalized task suggestions for a residence based on its home profile.
     * Requires authentication.
     */
    suspend fun getTaskSuggestions(token: String, residenceId: Int): ApiResult<TaskSuggestionsResponse> {
        return try {
            val response = client.get("$baseUrl/tasks/suggestions/") {
                header("Authorization", "Token $token")
                parameter("residence_id", residenceId)
            }

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

    /**
     * Get a single template by ID
     */
    suspend fun getTemplate(id: Int): ApiResult<TaskTemplate> {
        return try {
            val response = client.get("$baseUrl/tasks/templates/$id/")

            if (response.status.isSuccess()) {
                ApiResult.Success(response.body())
            } else {
                ApiResult.Error("Template not found", response.status.value)
            }
        } catch (e: Exception) {
            ApiResult.Error(e.message ?: "Unknown error occurred")
        }
    }
}
