package com.devlab.app.data.repository

import com.devlab.app.data.api.RetrofitClient
import com.devlab.app.data.model.LoginRequest
import com.devlab.app.data.model.RegisterRequest

class AuthRepository {

    suspend fun login(username: String, password: String): Result<LoginResult> {
        return try {
            val service = RetrofitClient.getUnauthenticatedService()
            val response = service.login(LoginRequest(username, password))
            if (response.success && response.data != null) {
                val token = response.data.token
                val user = response.data.user
                if (token.isNotBlank() && user != null) {
                    Result.success(LoginResult(token, user.id, user.username, user.email, user.role))
                } else {
                    Result.failure(Exception("Empty token received"))
                }
            } else {
                Result.failure(Exception(response.error ?: "Authentication failed"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    suspend fun register(username: String, email: String, password: String, confirmPassword: String): Result<LoginResult> {
        return try {
            val service = RetrofitClient.getUnauthenticatedService()
            val response = service.register(RegisterRequest(username, email, password, confirmPassword))
            if (response.success && response.data != null) {
                val token = response.data.token
                val user = response.data.user
                if (token.isNotBlank() && user != null) {
                    Result.success(LoginResult(token, user.id, user.username, user.email, user.role))
                } else {
                    Result.failure(Exception("Registration succeeded but empty token"))
                }
            } else {
                Result.failure(Exception(response.error ?: "Registration failed"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}

data class LoginResult(
    val token: String,
    val userId: Int,
    val username: String,
    val email: String,
    val role: String
)
