package com.example.profile

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class Profile(val id: String, val name: String, val avatarUrl: String?)

interface ProfileApi {
    suspend fun fetch(id: String): Profile?
    suspend fun upload(profile: Profile)
}

class ProfileRepository(
    private val api: ProfileApi,
    private val scope: CoroutineScope,
) {
    private val current = MutableStateFlow<Profile?>(null)

    val profile: StateFlow<Profile?> = current.asStateFlow()

    fun refresh(id: String) {
        scope.launch { current.value = api.fetch(id) }
    }

    fun avatar(): String = current.value?.avatarUrl ?: DEFAULT_AVATAR

    companion object {
        const val DEFAULT_AVATAR = "res://avatar"
    }
}
