package com.narutohuo.xindazhou.user.datasource.remote

import com.narutohuo.xindazhou.common.network.ApiResponseParser
import com.narutohuo.xindazhou.common.network.ApiServiceFactory
import com.narutohuo.xindazhou.user.model.LoginRequest
import com.narutohuo.xindazhou.user.model.LoginResponse
import com.narutohuo.xindazhou.user.model.RegisterRequest

/**
 * 认证远程数据源接口
 */
interface AuthRemoteDataSource {
    /**
     * 用户登录
     */
    suspend fun login(request: LoginRequest): Result<LoginResponse>
    
    /**
     * 用户注册
     */
    suspend fun register(request: RegisterRequest): Result<LoginResponse>
    
    /**
     * 刷新 Token
     */
    suspend fun refreshToken(refreshToken: String): Result<LoginResponse>
}

/**
 * 认证远程数据源实现
 */
class AuthRemoteDataSourceImpl : AuthRemoteDataSource {
    
    companion object {
        private const val TAG = "AuthRemoteDataSource"
    }
    
    private val authApi: AuthApi by lazy {
        ApiServiceFactory.create<AuthApi>()
    }
    
    override suspend fun login(request: LoginRequest): Result<LoginResponse> {
        return try {
            ApiResponseParser.handleResponse(
                response = authApi.login(request),
                dataClass = LoginResponse::class.java,
                tag = "$TAG - login",
                errorMessage = "登录失败"
            )
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    override suspend fun register(request: RegisterRequest): Result<LoginResponse> {
        return try {
            ApiResponseParser.handleResponse(
                response = authApi.register(request),
                dataClass = LoginResponse::class.java,
                tag = "$TAG - register",
                errorMessage = "注册失败"
            )
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    override suspend fun refreshToken(refreshToken: String): Result<LoginResponse> {
        return try {
            ApiResponseParser.handleResponse(
                response = authApi.refreshToken(refreshToken),
                dataClass = LoginResponse::class.java,
                tag = "$TAG - refreshToken",
                errorMessage = "Token 刷新失败"
            )
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}

