VcsFileController.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.controller

import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.media.Content
import io.swagger.v3.oas.annotations.media.Schema
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.tags.Tag
import org.archtool.data.dto.BranchInfoDto
import org.archtool.data.dto.ErrorResponseDto
import org.archtool.data.dto.PageDto
import org.archtool.provider.VcsProvider
import org.archtool.service.VcsFileReadFacade
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

@Tag(
    name = "Контроллер файловых операций VCS",
    description = "Чтение файлов и коммитов из локального зеркала активного VCS-провайдера. " +
        "Пути /bitbucket/* — алиасы того же обработчика"
)
@RestController
@RequestMapping("/api/v1/vcs", "/bitbucket")
class VcsFileController(
    private val vcsFileReadFacade: VcsFileReadFacade,
    private val vcsProvider: VcsProvider,
) {
    @Operation(
        summary = "Получение файла",
        description = "Возвращает содержимое файла в определённой ветке репозитория активного VCS-провайдера",
        responses = [
            ApiResponse(
                responseCode = "200", description = "Успех",
                content = [Content(schema = Schema(implementation = ByteArray::class))]
            ),
            ApiResponse(
                responseCode = "404", description = "Репозиторий, ветка или файл не найдены",
                content = [Content(schema = Schema(implementation = ErrorResponseDto::class))]
            )
        ]
    )
    @GetMapping("/file/{*path}")
    suspend fun getFile(
        @Parameter(description = "Ключ проекта Bitbucket. Для GitLab не передаётся")
        @RequestParam(required = false) project: String?,
        @Parameter(description = "Слаг репозитория Bitbucket или числовой id проекта GitLab", required = true)
        @RequestParam repo: String,
        @Parameter(description = "Имя ветки репозитория", required = true)
        @RequestParam branch: String,
        @Parameter(description = "Путь к файлу внутри репозитория", required = true)
        @PathVariable path: String
    ): ResponseEntity<ByteArray> {
        val fileRequest = vcsProvider.parseFileRequest(project, repo, branch)
        return vcsFileReadFacade.readFile(fileRequest, path)
    }

    @Operation(
        summary = "Получение хеша коммита",
        description = "Возвращает хеш коммита в определённой ветке репозитория активного VCS-провайдера",
        responses = [
            ApiResponse(
                responseCode = "200", description = "Успех",
                content = [Content(schema = Schema(implementation = PageDto::class))]
            ),
            ApiResponse(
                responseCode = "404", description = "Репозиторий, ветка или файл не найдены",
                content = [Content(schema = Schema(implementation = ErrorResponseDto::class))]
            )
        ]
    )
    @GetMapping("/commit/hash")
    suspend fun getCommitHash(
        @Parameter(description = "Ключ проекта Bitbucket. Для GitLab не передаётся")
        @RequestParam(required = false) project: String?,
        @Parameter(description = "Слаг репозитория Bitbucket или числовой id проекта GitLab", required = true)
        @RequestParam repo: String,
        @Parameter(description = "Имя ветки репозитория", required = true)
        @RequestParam branch: String
    ): ResponseEntity<PageDto<BranchInfoDto>> {
        val fileRequest = vcsProvider.parseFileRequest(project, repo, branch)
        return vcsFileReadFacade.readCommitHash(fileRequest)
    }
}