package com.carmaintenance.data.repository

import com.carmaintenance.data.manager.TokenManager
import com.carmaintenance.data.model.LoginRequest
import com.carmaintenance.data.model.User
import com.carmaintenance.data.remote.ApiResponse
import com.carmaintenance.data.remote.ApiService
import com.google.gson.Gson
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class AuthRepository @Inject constructor(
    private val apiService: ApiService,
    private val tokenManager: TokenManager
) {
    suspend fun login(username: String, password: String): Result<User> {
        return try {
            val response = apiService.login(LoginRequest(username, password))
            if (response.isSuccess && response.data != null) {
                // 保存Token
                tokenManager.saveToken(response.data.token)
                // 保存用户信息
                val userJson = Gson().toJson(response.data.userInfo)
                tokenManager.saveUserInfo(userJson)
                Result.success(response.data.userInfo)
            } else {
                Result.failure(Exception(response.message ?: "登录失败"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    suspend fun logout(): Result<Unit> {
        return try {
            apiService.logout()
            tokenManager.clearToken()
            Result.success(Unit)
        } catch (e: Exception) {
            tokenManager.clearToken()
            Result.success(Unit)
        }
    }

    suspend fun getCurrentUser(): User? {
        return try {
            val userJson = tokenManager.getUserInfo()
            if (userJson != null) {
                Gson().fromJson(userJson, User::class.java)
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }

    fun getCurrentUserFlow() = tokenManager.getUserInfoFlow()
}
