package space.nstart.pcp_tgu_service.service

import io.camunda.client.CamundaClient
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import space.nstart.pcp_tgu_service.dto.CreateSatelliteMissionVariables
import space.nstart.pcp_tgu_service.dto.ProcessStartResponse
import space.nstart.pcp_tgu_service.entity.PlanIssueAttemptEntity
import space.nstart.pcp_tgu_service.entity.PlannedPlanEntity

/**
 * Adapter, который стартует BPMN process instance для уже созданной attempt.
 */
@Service
class BpmnPlanIssueProcessStarter(
    private val camundaClient: CamundaClient
) {
    private val log = LoggerFactory.getLogger(javaClass)

    /** Стартует createSatelliteMission и возвращает ключ process instance. */
    fun startProcess(plan: PlannedPlanEntity, attempt: PlanIssueAttemptEntity): ProcessStartResponse {
        val variables = CreateSatelliteMissionVariables(
            spacecraftId = plan.spacecraftId,
            satellitePlanId = plan.planId.toString(),
            satellitePlanAttemptId = attempt.attemptId.toString(),
            planStartTime = plan.startTime,
            planEndTime = plan.endTime,
            kppId = plan.kppId
        )

        val processInstance = camundaClient
            .newCreateInstanceCommand()
            .bpmnProcessId(CREATE_SATELLITE_MISSION_PROCESS_ID)
            .latestVersion()
            .variables(variables)
            .send()
            .join()

        log.info(
            "Started BPMN plan issue process. processInstanceKey={}, spacecraftId={}, planId={}, attemptId={}",
            processInstance.processInstanceKey,
            plan.spacecraftId,
            plan.planId,
            attempt.attemptId
        )

        return ProcessStartResponse(
            processInstanceKey = processInstance.processInstanceKey,
            processDefinitionKey = processInstance.processDefinitionKey,
            bpmnProcessId = processInstance.bpmnProcessId,
            version = processInstance.version,
            planId = plan.planId,
            attemptId = attempt.attemptId
        )
    }

    private companion object {
        const val CREATE_SATELLITE_MISSION_PROCESS_ID = "createSatelliteMission"
    }
}
