OrganizationService.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

  In any derivative products, you must retain the information of
  owner of the original code and provide clear attribution to the project

  https://dochub.info

  The use of this product or its derivatives for any purpose cannot be a secret.


  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.

  Maintainers:
      Alexander Romashin <romashin.a.va@sberbank.ru>, Sber - 2026

  Contributors:
      Alexander Romashin <romashin.a.va@sberbank.ru>, Sber - 2026
      Марат Ниязматов <mrusniyazmatov@sberbank.ru>, Sber - 2026
*/

package org.archtool.service

import org.archtool.configuration.VcsProperties
import org.archtool.data.entity.OrganizationEntity
import org.archtool.data.entity.RepoOrganizationEntity
import org.archtool.data.model.SeafPermission
import org.archtool.vcs.provider.VcsRepoLinkFormat
import org.archtool.repository.OrganizationRepository
import org.archtool.repository.RepoOrganizationRepository
import org.archtool.repository.RepoRepository
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 OrganizationService(
    private val organizationRepository: OrganizationRepository,
    private val repoRepository: RepoRepository,
    private val repoOrganizationRepository: RepoOrganizationRepository,
    private val vcsProperties: VcsProperties,
    private val vcsRepoLinkFormat: VcsRepoLinkFormat,
) {
    private val log: Logger = LoggerFactory.getLogger(javaClass)

    @Transactional
    suspend fun insertOrganizationIfNotExistsAndSaveRepoRelations(
        externalOrgId: String,
        orgName: String,
        repos: List<String>,
        sequence: Long,
        expirationTime: Instant,
    ): OrganizationEntity {
        val existingOrg = organizationRepository.findByExternalOrgIdAndSequence(externalOrgId, sequence)
        val organizationEntity = if (existingOrg != null) {
            log.trace("Организация {} уже существует в БД, повторно не сохраняем", externalOrgId)
            existingOrg
        } else {
            val organizationEntity = OrganizationEntity(
                organizationId = UUID.randomUUID(),
                name = orgName,
                externalOrgId = externalOrgId,
                sequence = sequence,
                lastUpdateTime = Instant.now(),
                creationTime = Instant.now(),
                expirationTime = expirationTime,
                new = true
            )
            log.trace("Сохраняем новую организацию {} в БД", externalOrgId)
            organizationRepository.save(organizationEntity)
        }

        val vcsProvider = vcsProperties.provider
        for (repoString in repos) {
            val storageKey = vcsRepoLinkFormat.parseRepo(repoString)
            if (storageKey == null) {
                log.warn(
                    "externalOrgId={}: неверный формат строки репозитория: {}",
                    organizationEntity.externalOrgId,
                    repoString,
                )
                continue
            }
            val repoEntity = repoRepository.findBySequenceAndVcsProviderAndProjectKeyAndSlug(
                sequence,
                vcsProvider,
                storageKey.projectKey,
                storageKey.slug,
            )
            if (repoEntity != null) {
                val key = RepoOrganizationEntity.Key(repoEntity.repoId, organizationEntity.organizationId)
                if (repoOrganizationRepository.existsById(key)) {
                    log.trace(
                        "externalOrgId={}: связь организации с репозиторием {}:{} уже существует, завершаем обработку",
                        organizationEntity.externalOrgId,
                        storageKey.projectKey,
                        storageKey.slug,
                    )
                    continue
                }

                val repoOrgEntity = RepoOrganizationEntity(
                    key = key,
                    permission = SeafPermission.READ,
                    new = true
                )
                repoOrganizationRepository.save(repoOrgEntity)
                log.trace(
                    "externalOrgId={}: сохранена связь организации с репозиторием {}:{}",
                    organizationEntity.externalOrgId,
                    storageKey.projectKey,
                    storageKey.slug,
                )
            } else {
                log.trace(
                    "externalOrgId={}: репозиторий {}:{} не найден в БД, пропускаем сохранение связи",
                    organizationEntity.externalOrgId,
                    storageKey.projectKey,
                    storageKey.slug,
                )
            }
        }

        return organizationEntity
    }
}