ContextResolver.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:
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025

  Contributors:
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025
*/

package org.archtool.archloader.service.zip.income

import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import org.archtool.archloader.controller.api.dto.SeafJwt
import org.archtool.archloader.exception.UserDataException
import org.archtool.archloader.service.dto.ArchZipMeta
import org.archtool.archloader.service.dto.UploadContext
import org.archtool.archloader.service.integraion.core.SeafCoreClient
import org.archtool.archloader.service.zip.FileConst

@Component
class ContextResolver(
    private val seafCoreClient: SeafCoreClient,
    private val ruleTypes: Set<String>,
) {

    private val log = LoggerFactory.getLogger(javaClass)

    fun resolve(meta: ArchZipMeta, seafJwt: SeafJwt): UploadContext {
        if (!ruleTypes.contains(meta.type)) {
            throw UserDataException("${FileConst.META_JSON_FILE_NAME} содержит не поддерживаемый тип архитектуры ${meta.type}, допустимы только $ruleTypes")
        }

        val aboutAlias = seafCoreClient.getAboutAlias(alias = meta.domain, jwt = seafJwt)

        // просто проверка, что у пользователь есть доступ к этому alias
        val permission = seafJwt.permissions.firstOrNull { it.rp.equals(other = aboutAlias.permission, ignoreCase = true) }
        if (permission == null) {
            log.trace("Искали право {}, не нашли в списке {}, сравниваем игнорируя регистр", aboutAlias.permission, seafJwt.permissions.map { it.rp })
            log.error(
                "Для обработки домена {} требуется право {}, у пользователя его нет",
                meta.domain,
                aboutAlias.permission
            )
            throw UserDataException(
                "Отсутствуют права доступа к информации компании ${meta.domain}. " +
                        "Проверьте корректность заполнения domain или запросите у курирующего архитектора точный элиас (alias) компании"
            )
        }

        val repoInfo = aboutAlias.repos?.firstOrNull { it.type == meta.type }
            ?: throw UserDataException("Для домена ${meta.domain} не указан репозиторий для типа ${meta.type}")

        return UploadContext(
            repoInfo = repoInfo
        )
    }
}