package com.radiola.data.repository

import com.radiola.data.local.TokenDataStore
import com.radiola.data.remote.RadiolaApi
import com.radiola.data.remote.dto.MagicLinkRequestDto
import com.radiola.data.remote.dto.MagicLinkVerifyDto
import com.radiola.domain.model.User
import com.radiola.domain.repository.AuthRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class AuthRepositoryImpl @Inject constructor(
    private val api: RadiolaApi,
    private val tokenDataStore: TokenDataStore
) : AuthRepository {

    override suspend fun requestMagicLink(email: String): Result<Unit> = try {
        api.requestMagicLink(MagicLinkRequestDto(email))
        Result.success(Unit)
    } catch (e: Exception) {
        Result.failure(e)
    }

    override suspend fun verifyMagicLink(email: String, code: String): Result<User> = try {
        val response = api.verifyMagicLink(MagicLinkVerifyDto(email, code))
        tokenDataStore.saveToken(
            token = response.accessToken,
            userId = response.user.id,
            email = response.user.email,
            name = response.user.name
        )
        Result.success(
            User(
                id = response.user.id,
                email = response.user.email,
                name = response.user.name
            )
        )
    } catch (e: Exception) {
        Result.failure(e)
    }

    override fun isLoggedIn(): Flow<Boolean> = tokenDataStore.isLoggedIn

    override fun currentUser(): Flow<User?> = combine(
        tokenDataStore.userId,
        tokenDataStore.userEmail,
        tokenDataStore.userName
    ) { id, email, name ->
        if (id != null && email != null) {
            User(id = id, email = email, name = name)
        } else null
    }

    override suspend fun logout() {
        tokenDataStore.clear()
    }
}
