package de.trainingstagebuch.app.services

import de.trainingstagebuch.app.core.SessionData
import de.trainingstagebuch.app.core.SessionManager
import de.trainingstagebuch.app.repository.LoginResult
import de.trainingstagebuch.app.repository.RegisterResult
import de.trainingstagebuch.app.repository.ActivateResult
import de.trainingstagebuch.app.repository.ForgotPasswordResult
import de.trainingstagebuch.app.repository.ResetPasswordResult
import de.trainingstagebuch.app.repository.TrainingstagebuchRepository
import kotlinx.coroutines.flow.Flow

class AuthService(
    private val sessionManager: SessionManager,
    private val repository: TrainingstagebuchRepository
) {
    val session: Flow<SessionData> = sessionManager.session

    suspend fun login(email: String, password: String): LoginResult {
        val result = repository.login(email, password)
        if (result is LoginResult.Success) {
            sessionManager.save(token = result.token, username = email, currentClub = null)
            repository.connectSocketOnLogin()
        }
        return result
    }

    suspend fun register(email: String, password: String): RegisterResult {
        return repository.register(email, password)
    }

    suspend fun activate(activationCode: String): ActivateResult {
        return repository.activate(activationCode)
    }

    suspend fun forgotPassword(email: String): ForgotPasswordResult {
        return repository.forgotPassword(email)
    }

    suspend fun resetPassword(token: String, password: String): ResetPasswordResult {
        return repository.resetPassword(token, password)
    }

    suspend fun saveCurrentClub(token: String?, username: String?, clubId: String?) {
        sessionManager.save(token = token, username = username, currentClub = clubId)
    }

    suspend fun logout() {
        repository.disconnectSocketOnLogout()
        sessionManager.logout()
    }
}
