package com.example.initiateaphonecallapp.data.repository

import com.example.initiateaphonecallapp.data.model.GetCodeRequest
import com.example.initiateaphonecallapp.data.model.LoginRequest
import com.example.initiateaphonecallapp.data.model.LoginResponse
import com.example.initiateaphonecallapp.data.model.LoginSmsRequest
import com.example.initiateaphonecallapp.data.network.RetrofitClient
import com.example.initiateaphonecallapp.data.network.RetrofitClient.loginApiService
import retrofit2.HttpException  // 正确的导入
import java.io.IOException

class AuthRepository {
    private val apiService = RetrofitClient.loginApiService

    // 移除 @RequiresExtension 注解，它在这里不需要
    suspend fun login(username: String, password: String): Result<LoginResponse> {
        return try {
            val request = LoginRequest(username, password)
            val response = apiService.login(request)
            println("Response code: ${response.code()}")
            println("Response body: ${response.body()}")
            if (response.isSuccessful && response.body() != null) {
                val responseBody = response.body()!!
                if (responseBody.code == 200) { // 假设200表示业务成功
                    Result.success(responseBody)
                } else {
                    // 使用服务器返回的消息，如果没有则使用默认消息
                    val errorMessage = responseBody.msg ?: "登录失败"
                    Result.failure(Exception(errorMessage))
                }

            } else {
                println("Login failed with error code: ${response.code()}")
                // 获取具体的错误信息
                val errorCode = response.code()
                val errorMessage = when (errorCode) {
                    400 -> "请求参数错误"
                    401 -> "用户名或密码错误"
                    403 -> "访问被拒绝"
                    404 -> "接口不存在"
                    500 -> "服务器内部错误"
                    else -> "登录失败 (错误码: $errorCode)"
                }
                Result.failure(Exception(errorMessage))
            }
        } catch (e: HttpException) {  // 现在这个会正确捕获 Retrofit 的 HTTP 异常
            // 处理 HTTP 异常
            val errorCode = e.code()
            val errorMessage = when (errorCode) {
                400 -> "请求参数错误"
                401 -> "用户名或密码错误"
                403 -> "访问被拒绝"
                404 -> "接口不存在"
                500 -> "服务器内部错误"
                else -> "网络错误: $errorCode ${e.message()}"
            }
            Result.failure(Exception(errorMessage))
        } catch (e: IOException) {
            Result.failure(Exception("网络连接失败，请检查网络设置"))
        } catch (e: Exception) {
            Result.failure(Exception("未知错误: ${e.message}"))
        }
    }

    // 获取验证码
    suspend fun getCode(phone: String): Result<Boolean> {
        return try {
            val response = apiService.getCode(GetCodeRequest(phone))
            if (response.isSuccessful) {
                val apiResponse = response.body()
                if (apiResponse?.code == 200 && apiResponse.data == true) {
                    Result.success(true)
                } else {
                    Result.failure(Exception(apiResponse?.message ?: "获取验证码失败"))
                }
            } else {
                Result.failure(Exception("网络请求失败: ${response.code()}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    // 验证码登录
    suspend fun loginSms(phone: String, code: String): Result<LoginResponse> {
        return try {
            val response = apiService.loginSms(LoginSmsRequest(phone, code))
            if (response.isSuccessful) {
                Result.success(response.body()!!)
            } else {
                Result.failure(Exception("Login failed: ${response.code()}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}