PermissionByOrgId.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.permission

import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import org.archtool.configuration.VcsProperties
import org.archtool.data.exception.TokenGenerationError
import org.archtool.data.model.RepoPermission
import org.archtool.helper.PermissionHelper
import org.archtool.vcs.provider.VcsRepoLinkFormat
import org.archtool.repository.OrganizationRepository
import org.archtool.repository.RepoOrganizationRepository
import org.archtool.repository.RepoRepository
import org.archtool.service.SettingsService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service

@Service
class PermissionByOrgId(
    private val organizationRepository: OrganizationRepository,
    private val repoOrganizationRepository: RepoOrganizationRepository,
    private val repoRepository: RepoRepository,
    private val settingsService: SettingsService,
    private val permissionHelper: PermissionHelper,
    private val vcsRepoLinkFormat: VcsRepoLinkFormat,
    private val vcsProperties: VcsProperties,
) {

    private val log: Logger = LoggerFactory.getLogger(javaClass)

    suspend fun fetch(organisation: String?): List<RepoPermission> {
        if (organisation == null) {
            log.debug("parameter 'organisation' is null, return empty list of permission")
            return emptyList()
        }
        val sequence = settingsService.getActiveSequence()
            ?: throw TokenGenerationError("Не найден номер активной последовательности")
        log.trace("Получен sequence number {}", sequence)

        val orgEntity = organizationRepository.findByExternalOrgIdAndSequence(organisation, sequence)
            ?: throw TokenGenerationError("Не найдена организация с externalOrgId: $organisation и sequence: $sequence")
        log.trace("[{}] Найдена организация '{}' с ID {}", organisation, orgEntity.name, orgEntity.organizationId)

        val repoOrgEntities = repoOrganizationRepository.findByKeyOrganizationId(orgEntity.organizationId)
        val orgPermissions = repoOrgEntities.map { repoOrgEntity ->
            val repoEntity = repoRepository.findById(repoOrgEntity.key.repoId)
            if (repoEntity == null) {
                log.warn("[{}] Репозиторий с ID {} не найден в БД", organisation, repoOrgEntity.key.repoId)
                return@map null
            } else if (repoEntity.vcsProvider != vcsProperties.provider) {
                log.warn("[{}] Репозиторий с ID {} найден, но другой провайдер, ожидался {} а получен {}, в итоговый список permission не попадёт",
                    organisation,
                    repoOrgEntity.key.repoId,
                    vcsProperties.provider,
                    repoEntity.vcsProvider
                )
                return@map null
            }
            return@map RepoPermission(vcsRepoLinkFormat.prefix(repoEntity), repoOrgEntity.permission)
        }.filterNotNull().toList()

        return permissionHelper.sortByRp(orgPermissions)
    }
}