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.PipelineResponse
import com.example.initiateaphonecallapp.data.model.toCallRecords
import com.example.initiateaphonecallapp.data.network.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.Response

class PiplineRepository {
 private val  pipelineService = RetrofitClient.pipelineService


    suspend fun getPipelines(): Result<List<PipelineResponse>> {
        return withContext(Dispatchers.IO) {
            try {
                val response = pipelineService.getPiplines()
                handleResponse(response)
            } catch (e: Exception) {
                Result.failure(Exception("网络请求失败: ${e.message}"))
            }
        }
    }

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