package app.closer.data.repository

import app.closer.crypto.CoupleEncryptionManager
import app.closer.data.remote.FirestoreInviteDataSource
import app.closer.domain.model.Invite
import app.closer.domain.repository.AcceptInviteResult
import app.closer.domain.repository.CreateInviteResult
import app.closer.domain.repository.InviteRepository
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class InviteRepositoryImpl @Inject constructor(
    private val dataSource: FirestoreInviteDataSource,
    private val encryptionManager: CoupleEncryptionManager
) : InviteRepository {

    override suspend fun createInvite(inviterUserId: String): Result<CreateInviteResult> = runCatching {
        val code = dataSource.generateCode()
        val setup = encryptionManager.setupForNewCouple(code)
        dataSource.createInvite(code, inviterUserId, setup.wrapped)
        CreateInviteResult(code = code, recoveryPhrase = setup.recoveryPhrase)
    }

    override suspend fun getInviteByCode(code: String): Result<Invite?> = runCatching {
        dataSource.getInviteByCode(code)
    }

    override suspend fun acceptInvite(code: String, acceptorUserId: String, recoveryPhrase: String): Result<AcceptInviteResult> = runCatching {
        dataSource.acceptInvite(code, recoveryPhrase)
    }
}
