package com.example.elva.data.repository

import com.example.elva.data.api.AuthApiService
import com.example.elva.data.models.auth.AuthResponse
import com.example.elva.data.models.auth.LoginRequest
import com.example.elva.data.models.auth.RegisterRequest
import com.example.elva.util.AuthManager
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class AuthRepository @Inject constructor(
    private val authApi: AuthApiService,
    private val authManager: AuthManager
) {

    suspend fun register(
        username: String,
        email: String,
        password: String,
        fullName: String? = null,
        phone: String? = null
    ): Result<AuthResponse> {
        return try {
            val request = RegisterRequest(
                username = username,
                email = email,
                password = password,
                fullName = fullName,
                phone = phone
            )
            val response = authApi.register(request)

            // Сохраняем токен
            authManager.saveAuthData(
                token = response.accessToken,
                userId = 0, // ID будет получен позже через запрос профиля
                email = email,
                username = username
            )

            Result.success(response)
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    suspend fun login(
        email: String? = null,
        username: String? = null,
        password: String
    ): Result<AuthResponse> {
        return try {
            android.util.Log.d("AuthRepository", "login() called with: email=$email, username=$username")

            val request = LoginRequest(
                email = email,
                username = username,
                password = password
            )

            val response = authApi.login(request)
            android.util.Log.d("AuthRepository", "login response received: token=${response.accessToken.take(20)}...")

            // Сохраняем токен и данные пользователя
            val savedEmail = email ?: username ?: ""
            val savedUsername = username ?: email ?: ""

            android.util.Log.d("AuthRepository", "Saving auth data: email=$savedEmail, username=$savedUsername")

            authManager.saveAuthData(
                token = response.accessToken,
                userId = 0, // ID будет получен позже через запрос профиля
                email = savedEmail,
                username = savedUsername
            )

            android.util.Log.d("AuthRepository", "Auth data saved successfully")


            Result.success(response)
        } catch (e: Exception) {
            android.util.Log.e("AuthRepository", "login failed", e)
            Result.failure(e)
        }
    }

    fun logout() {
        authManager.logout()
    }

    fun isLoggedIn(): Boolean {
        return authManager.isLoggedIn()
    }
}

