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

import com.example.initiateaphonecallapp.data.model.ApiCallRecord
import com.example.initiateaphonecallapp.data.model.ApiResponse
import com.example.initiateaphonecallapp.data.model.CallRecord
import com.example.initiateaphonecallapp.data.model.CallRecordRequest
import com.example.initiateaphonecallapp.data.model.toCallRecords
import com.example.initiateaphonecallapp.data.network.ApiCallLogService
import com.example.initiateaphonecallapp.data.network.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.Response

class CallLogRepository(

) {
    private val apiCallLogService = RetrofitClient.apiCallLogService
    /**
     * 获取通话记录列表
     * @param request 时间范围请求参数
     * @return 通话记录列表的结果
     */
    suspend fun getCallLogs(request: CallRecordRequest): Result<List<CallRecord>> {
        return withContext(Dispatchers.IO) {
            try {
                val response = apiCallLogService.callLog(request)
                handleResponse(response)
            } catch (e: Exception) {
                Result.failure(Exception("网络请求失败: ${e.message}"))
            }
        }
    }

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