UserService.kt

/*
  Copyright (C) 2026 Sber

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package org.archtool.service

import org.archtool.configuration.VcsProperties
import org.archtool.vcs.provider.VcsProjectKey
import org.archtool.vcs.provider.VcsRepoLinkFormat
import org.archtool.vcs.provider.VcsRepoSlug
import org.archtool.vcs.provider.VcsUser
import org.archtool.data.entity.RepoUserEntity
import org.archtool.data.entity.UserEntity
import org.archtool.data.model.SeafPermission
import org.archtool.repository.RepoRepository
import org.archtool.repository.RepoUserRepository
import org.archtool.repository.UserRepository
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.Instant
import java.util.UUID

@Service
class UserService(
    private val userRepository: UserRepository,
    private val repoRepository: RepoRepository,
    private val repoUserRepository: RepoUserRepository,
    private val vcsProperties: VcsProperties,
    private val vcsRepoLinkFormat: VcsRepoLinkFormat,
) {
    private val log: Logger = LoggerFactory.getLogger(javaClass)

    @Transactional
    suspend fun insertUserIfNotExistsAndSaveRepoRelations(
        user: VcsUser,
        repoSlugs: Set<VcsRepoSlug>,
        projectKey: VcsProjectKey,
        sequence: Long,
        expirationTime: Instant,
        permission: SeafPermission
    ): UserEntity {
        val existingUser = userRepository.findByExternalUserIdAndSequence(user.externalId, sequence)
        val userEntity = if (existingUser != null) {
            log.trace("[{}] Пользователь уже существует в БД, повторно не сохраняем", user.externalId)
            existingUser
        } else {
            val userEntity = UserEntity(
                userId = UUID.randomUUID(),
                name = user.externalId,
                lastname = user.externalId,
                externalUserId = user.externalId,
                sequence = sequence,
                lastUpdateTime = Instant.now(),
                creationTime = Instant.now(),
                expirationTime = expirationTime,
                new = true
            )
            log.trace("[{}] Сохраняем нового пользователя в БД", user.externalId)
            userRepository.save(userEntity)
        }

        for (repoSlug in repoSlugs) {
            val storageKey = vcsRepoLinkFormat.storageKey(projectKey, repoSlug)
            val repoEntity = repoRepository.findBySequenceAndVcsProviderAndProjectKeyAndSlug(
                sequence,
                vcsProperties.provider,
                storageKey.projectKey,
                storageKey.slug,
            )
            if (repoEntity != null) {
                val key = RepoUserEntity.Key(repoEntity.repoId, userEntity.userId)
                val existingRelation = repoUserRepository.findById(key)

                if (existingRelation != null) {
                    val updatedRelation = existingRelation.copy(permission = permission)
                    log.trace(
                        "[{}] Обновляем permission связи пользователя с репозиторием {}:{}",
                        userEntity.name, projectKey, repoSlug
                    )
                    repoUserRepository.save(updatedRelation)
                } else {
                    val repoUserEntity = RepoUserEntity(
                        key = key,
                        permission = permission,
                        new = true
                    )
                    log.trace(
                        "[{}] Сохраняем новую связь пользователя с репозиторием {}:{}",
                        userEntity.name, projectKey, repoSlug
                    )
                    repoUserRepository.save(repoUserEntity)
                }
            } else {
                log.trace(
                    "[{}] Репозиторий {}:{} не найден в БД, пропускаем сохранение связи",
                    userEntity.name, projectKey, repoSlug
                )
            }
        }

        return userEntity
    }
}