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

*/

package org.archtool.controller

import com.github.kagkarlsson.scheduler.SchedulerClient
import com.github.kagkarlsson.scheduler.task.Task
import org.archtool.configuration.tasks.AccessUpdateTaskConfig
import org.archtool.data.dto.TaskStatusDto
import org.archtool.data.dto.TaskStatusResponseDto
import org.archtool.data.model.AccessUpdateTaskModel
import org.archtool.service.HistoryService
import org.slf4j.LoggerFactory
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RestController
import java.time.Instant

@RestController
class AccessUpdateTaskControllerImpl(
    private val schedulerClient: SchedulerClient,
    private val accessUpdateTask: Task<AccessUpdateTaskModel>,
    private val historyService: HistoryService
) : AccessUpdateTaskController {

    private val log = LoggerFactory.getLogger(javaClass)

    override fun update(): ResponseEntity<TaskStatusResponseDto> {
        val initialData = AccessUpdateTaskModel()
        val taskInstance = accessUpdateTask.instance(
            AccessUpdateTaskConfig.GLOBAL_INSTANCE_ID,
            initialData
        )
        val isScheduled = schedulerClient.scheduleIfNotExists(taskInstance, Instant.now())
        return if (isScheduled) {
            log.info("Процесс обновления seaf-ams успешно запущен.")
            ResponseEntity.ok(fetchCurrentStatus().copy(message = "Обновление seaf-ams запущено асинхронно"))
        } else {
            log.warn("Попытка дублирующего запуска. Процесс уже выполняется. Возвращаем текущий статус.")
            ResponseEntity.ok(fetchCurrentStatus().copy(message = "Попытка дублирующего запуска"))
        }
    }

    override fun status(): ResponseEntity<TaskStatusResponseDto> {
        return ResponseEntity.ok(fetchCurrentStatus())
    }

    private fun fetchCurrentStatus(): TaskStatusResponseDto {
        val execution = schedulerClient.getScheduledExecutionsForTask(
            AccessUpdateTaskConfig.TASK_NAME,
            AccessUpdateTaskModel::class.java
        ).find {
            it.taskInstance.taskName == AccessUpdateTaskConfig.TASK_NAME && it.taskInstance.id == AccessUpdateTaskConfig.GLOBAL_INSTANCE_ID
        }
        return TaskStatusResponseDto(
            orchestrator = execution?.data?.let {
                TaskStatusDto(
                    currentStep = it.currentStep.name
                )
            } ?: TaskStatusDto.idle(),
            history = historyService.getTaskHistory(AccessUpdateTaskConfig.TASK_NAME)
        )
    }
}