import request from '@/utils/request';
import type { 
  DeployEnvironmentsResponse, 
  StartDeploymentResponse, 
  PendingApprovalTask, 
  PendingApprovalTaskResponse,
  CompleteApprovalRequest 
} from './types';

const DEPLOY_URL = '/api/v1/deploy';

/**
 * 获取用户的部署环境列表
 */
export const getDeployEnvironments = () =>
  request.get<DeployEnvironmentsResponse>(`${DEPLOY_URL}/environments`);

/**
 * 发起部署
 * @param deployData 部署数据（包含表单填写的所有字段）
 */
export const startDeployment = (deployData: Record<string, any>) =>
  request.post<StartDeploymentResponse>(`${DEPLOY_URL}/execute`, deployData);

/**
 * 获取部署流程图数据
 * @param deployRecordId 部署记录ID
 */
export const getDeployRecordFlowGraph = (deployRecordId: number) =>
  request.get<import('./types').DeployRecordFlowGraph>(`${DEPLOY_URL}/records/${deployRecordId}/flow-graph`);

/**
 * 将后端返回的嵌套结构转换为前端扁平结构
 */
const transformApprovalTask = (response: PendingApprovalTaskResponse): PendingApprovalTask => {
  return {
    // 审批任务基本信息
    taskId: response.approvalTask.taskId,
    taskName: response.approvalTask.taskName,
    taskDescription: response.approvalTask.taskDescription,
    processInstanceId: response.approvalTask.processInstanceId,
    processDefinitionId: response.approvalTask.processDefinitionId,
    assignee: response.approvalTask.assignee || '',
    createTime: response.approvalTask.createTime,
    dueDate: response.approvalTask.dueDate || undefined,
    approvalTitle: response.approvalTask.approvalTitle,
    approvalContent: response.approvalTask.approvalContent,
    approvalMode: response.approvalTask.approvalMode,
    allowDelegate: response.approvalTask.allowDelegate,
    allowAddSign: response.approvalTask.allowAddSign,
    requireComment: response.approvalTask.requireComment,
    pendingDuration: response.approvalTask.pendingDuration,
    
    // 部署业务上下文信息
    deployRecordId: response.deployRecord.id,
    businessKey: response.deployRecord.businessKey,
    deployRemark: response.deployRecord.remark,
    deployStartTime: response.deployRecord.startTime,
    
    teamId: response.team.id,
    teamName: response.team.name,
    
    applicationId: response.application.id,
    applicationCode: response.application.code,
    applicationName: response.application.name,
    
    environmentId: response.environment.id,
    environmentCode: response.environment.code,
    environmentName: response.environment.name,
    
    // 部署人信息 - 优先使用 nickname，其次 username
    deployBy: response.deployUser.nickname || response.deployUser.username,
  };
};

/**
 * 获取我的待审批任务列表
 * @param workflowDefinitionKeys 工作流定义键列表（可选）
 * @param teamId 团队ID，用于筛选指定团队的审批任务（可选）
 * @param environmentId 环境ID，用于筛选指定环境的审批任务（可选）
 */
export const getMyApprovalTasks = async (
  workflowDefinitionKeys?: string[],
  teamId?: number,
  environmentId?: number
): Promise<PendingApprovalTask[]> => {
  const params: Record<string, any> = {};
  
  if (workflowDefinitionKeys && workflowDefinitionKeys.length > 0) {
    params.workflowDefinitionKeys = workflowDefinitionKeys.join(',');
  }
  
  if (teamId !== undefined) {
    params.teamId = teamId;
  }
  
  if (environmentId !== undefined) {
    params.environmentId = environmentId;
  }
  
  const response = await request.get<PendingApprovalTaskResponse[]>(
    `${DEPLOY_URL}/my-approval-tasks`, 
    { params }
  );
  
  // 将嵌套结构转换为扁平结构
  return response.map(transformApprovalTask);
};

/**
 * 完成审批
 */
export const completeApproval = (data: CompleteApprovalRequest) =>
  request.post(`${DEPLOY_URL}/complete`, data);

/**
 * 获取部署节点日志
 * @param processInstanceId 流程实例ID
 * @param nodeId 节点ID
 */
export const getDeployNodeLogs = (processInstanceId: string, nodeId: string) =>
  request.get<import('./types').DeployNodeLogDTO>(`${DEPLOY_URL}/logs`, {
    params: { processInstanceId, nodeId }
  });
