// data/repository/ContactsRepository.kt
package com.example.initiateaphonecallapp.data.repository

import com.example.initiateaphonecallapp.data.model.ApiContactsRequest
import com.example.initiateaphonecallapp.data.model.ApiContactsResponse
import com.example.initiateaphonecallapp.data.model.ApiResponse
import com.example.initiateaphonecallapp.data.network.ApiContactsService
import com.example.initiateaphonecallapp.data.network.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.Response

class ContactsRepository (
) {

    private val apiContactsService = RetrofitClient.apiContactsService
    /**
     * 添加联系人
     * @param name 联系人姓名
     * @param phone 联系人电话
     * @return 添加联系人的结果
     */
    suspend fun addContact(name: String, phone: String): Result<ApiContactsResponse> {
        return withContext(Dispatchers.IO) {
            try {
                val request = ApiContactsRequest(name = name, phone = phone)
                val response = apiContactsService.addContact(request)
                handleResponse(response)
            } catch (e: Exception) {
                Result.failure(Exception("添加联系人失败: ${e.message}"))
            }
        }
    }

    /**
     * 获取联系人
     */
    suspend fun listContacts(): Result<ApiResponse<List<ApiContactsRequest>>> {
        return withContext(Dispatchers.IO) {
            try {
                val response = apiContactsService.listContacts()
                handleResponse2(response)
            } catch (e: Exception) {
                Result.failure(Exception(" ${e.message}"))
            }
        }
    }


    /**
     * 处理 API 响应
     */
    private fun handleResponse(response: Response<ApiContactsResponse>): Result<ApiContactsResponse> {
        return when {
            response.isSuccessful -> {
                val apiResponse = response.body()
                when (apiResponse?.code) {
                    200 -> Result.success(apiResponse)
                    else -> {
                        Result.failure(Exception(apiResponse?.msg ?: "未知错误"))
                    }
                }
            }
            else -> {
                Result.failure(Exception("网络错误: ${response.code()} ${response.message()}"))
            }
        }
    }


    private fun handleResponse2(response: Response<ApiResponse<List<ApiContactsRequest>>>): Result<ApiResponse<List<ApiContactsRequest>>> {
        return when {
            response.isSuccessful -> {
                val apiResponse = response.body()
                when (apiResponse?.code) {
                    200 -> Result.success(apiResponse)
                    else -> {
                        Result.failure(Exception( "未知错误"))
                    }
                }
            }
            else -> {
                Result.failure(Exception("网络错误: ${response.code()} ${response.message()}"))
            }
        }
    }
}