package com.qqchen.deploy.backend.deploy.api;

import com.qqchen.deploy.backend.deploy.dto.*;
import com.qqchen.deploy.backend.deploy.service.IDeployRecordService;
import com.qqchen.deploy.backend.deploy.service.IDeployService;
import com.qqchen.deploy.backend.framework.api.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 部署管理API控制器
 *
 * @author qqchen
 * @since 2025-11-02
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/deploy")
@Tag(name = "部署管理", description = "部署相关接口")
public class DeployApiController {

    @Resource
    private IDeployService deployService;

    @Resource
    private IDeployRecordService deployRecordService;

    /**
     * 获取当前用户可部署的环境和应用
     */
    @Operation(summary = "获取可部署的环境", description = "获取当前登录用户在各团队中可部署的环境和应用列表")
    @GetMapping("/environments")
    @PreAuthorize("isAuthenticated()")
    public Response<List<UserTeamDeployableDTO>> getDeployableEnvironments() {
        return Response.success(deployService.getDeployableEnvironments());
    }

    /**
     * 执行部署
     */
    @Operation(summary = "执行部署", description = "根据团队应用配置启动部署工作流")
    @PostMapping("/execute")
    @PreAuthorize("isAuthenticated()")
    public Response<DeployResultDTO> executeDeploy(@Validated @RequestBody DeployExecuteRequest request) {
        return Response.success(deployService.executeDeploy(request));
    }

    /**
     * 获取部署记录的流程图
     * 用于前端展示工作流的流程图和节点执行状态
     */
    @Operation(summary = "获取部署流程图", description = "获取指定部署记录的工作流流程图数据，包含流程图结构和节点执行状态")
    @GetMapping("/records/{deployRecordId}/flow-graph")
    @PreAuthorize("isAuthenticated()")
    public Response<DeployRecordFlowGraphDTO> getDeployFlowGraph(
        @Parameter(description = "部署记录ID", required = true) @PathVariable Long deployRecordId
    ) {
        return Response.success(deployRecordService.getDeployFlowGraph(deployRecordId));
    }

    /**
     * 获取当前用户的部署审批任务列表
     */
    @Operation(summary = "获取我的部署审批任务", description = "查询当前登录用户待审批的部署任务，支持按团队和环境筛选")
    @GetMapping("/my-approval-tasks")
    @PreAuthorize("isAuthenticated()")
    public Response<List<DeployApprovalTaskDTO>> getMyApprovalTasks(@Parameter(description = "团队ID（可选，用于筛选指定团队的审批任务）") @RequestParam(required = false) Long teamId,
                                                                    @Parameter(description = "环境ID（可选，用于筛选指定环境的审批任务）") @RequestParam(required = false) Long environmentId,
                                                                    @Parameter(description = "工作流定义Key列表（可选，支持查询多个工作流的待审批任务）") @RequestParam(required = false) List<String> workflowDefinitionKeys
    ) {
        return Response.success(deployService.getMyApprovalTasks(teamId, environmentId, workflowDefinitionKeys));
    }

    /**
     * 完成部署审批
     */
    @Operation(summary = "完成部署审批", description = "完成部署审批任务，后续节点（Jenkins构建、通知等）将由Flowable异步执行")
    @PostMapping("/complete")
    @PreAuthorize("isAuthenticated()")
    public Response<Void> completeApproval(@Validated @RequestBody DeployApprovalCompleteRequest request) {
        deployService.completeApproval(request);
        return Response.success();
    }

    /**
     * 获取节点日志
     */
    @Operation(summary = "获取节点日志", description = "获取指定节点的执行日志，日志保留7天，超过7天将被清除")
    @GetMapping("/logs")
    @PreAuthorize("isAuthenticated()")
    public Response<DeployNodeLogDTO> getNodeLogs(
        @Parameter(description = "流程实例ID", required = true) @RequestParam String processInstanceId,
        @Parameter(description = "节点ID", required = true) @RequestParam String nodeId
    ) {
        return Response.success(deployService.getNodeLogs(processInstanceId, nodeId));
    }
}

