package top.yeij.cyrene.data.repository

import top.yeij.cyrene.data.local.PreferencesDataStore
import top.yeij.cyrene.data.remote.ApiService
import top.yeij.cyrene.data.remote.AuthInterceptor
import top.yeij.cyrene.data.remote.dto.AuthRequest
import top.yeij.cyrene.domain.model.AuthResult
import top.yeij.cyrene.domain.repository.AuthRepository
import kotlinx.coroutines.flow.firstOrNull

class AuthRepositoryImpl(
    private val apiService: ApiService,
    private val preferencesDataStore: PreferencesDataStore,
    private val authInterceptor: AuthInterceptor,
) : AuthRepository {

    override suspend fun login(username: String, password: String): Result<AuthResult> {
        return try {
            val response = apiService.login(AuthRequest(username, password))
            if (response.isSuccessful) {
                val body = response.body()!!
                authInterceptor.token = body.token
                preferencesDataStore.saveToken(body.token)
                body.refreshToken?.let { preferencesDataStore.saveRefreshToken(it) }
                val displayName = body.nickname ?: body.username ?: body.userId ?: "开拓者"
                preferencesDataStore.saveUsername(displayName)
                Result.success(
                    AuthResult(
                        token = body.token,
                        refreshToken = body.refreshToken,
                        username = displayName,
                    )
                )
            } else {
                Result.failure(Exception("登录失败: ${response.code()}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    override suspend fun logout() {
        authInterceptor.token = null
        preferencesDataStore.clearAll()
    }

    override suspend fun isLoggedIn(): Boolean {
        return preferencesDataStore.token.firstOrNull() != null
    }
}
