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

    suspend fun getContractors(
        token: String,
        specialty: String? = null,
        isFavorite: Boolean? = null,
        isActive: Boolean? = null,
        search: String? = null
    ): ApiResult<List<ContractorSummary>> {
        return try {
            val response = client.get("$baseUrl/contractors/") {
                header("Authorization", "Token $token")
                specialty?.let { parameter("specialty", it) }
                isFavorite?.let { parameter("is_favorite", it) }
                isActive?.let { parameter("is_active", it) }
                search?.let { parameter("search", it) }
            }

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

    suspend fun getContractor(token: String, id: Int): ApiResult<Contractor> {
        return try {
            val response = client.get("$baseUrl/contractors/$id/") {
                header("Authorization", "Token $token")
            }

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

    suspend fun createContractor(token: String, request: ContractorCreateRequest): ApiResult<Contractor> {
        return try {
            val response = client.post("$baseUrl/contractors/") {
                header("Authorization", "Token $token")
                contentType(ContentType.Application.Json)
                setBody(request)
            }

            if (response.status.isSuccess()) {
                ApiResult.Success(response.body())
            } else {
                val errorBody = try {
                    response.body<String>()
                } catch (e: Exception) {
                    "Failed to create contractor"
                }
                ApiResult.Error(errorBody, response.status.value)
            }
        } catch (e: Exception) {
            ApiResult.Error(e.message ?: "Unknown error occurred")
        }
    }

    suspend fun updateContractor(token: String, id: Int, request: ContractorUpdateRequest): ApiResult<Contractor> {
        return try {
            val response = client.patch("$baseUrl/contractors/$id/") {
                header("Authorization", "Token $token")
                contentType(ContentType.Application.Json)
                setBody(request)
            }

            if (response.status.isSuccess()) {
                ApiResult.Success(response.body())
            } else {
                val errorBody = try {
                    response.body<String>()
                } catch (e: Exception) {
                    "Failed to update contractor"
                }
                ApiResult.Error(errorBody, response.status.value)
            }
        } catch (e: Exception) {
            ApiResult.Error(e.message ?: "Unknown error occurred")
        }
    }

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

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

    suspend fun toggleFavorite(token: String, id: Int): ApiResult<Contractor> {
        return try {
            val response = client.post("$baseUrl/contractors/$id/toggle-favorite/") {
                header("Authorization", "Token $token")
            }

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

    suspend fun getContractorTasks(token: String, id: Int): ApiResult<List<TaskResponse>> {
        return try {
            val response = client.get("$baseUrl/contractors/$id/tasks/") {
                header("Authorization", "Token $token")
            }

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

    suspend fun getContractorsByResidence(token: String, residenceId: Int): ApiResult<List<ContractorSummary>> {
        return try {
            val response = client.get("$baseUrl/contractors/by-residence/$residenceId/") {
                header("Authorization", "Token $token")
            }

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