import request from '@/utils/request';
import {WorkflowDefinition, WorkflowDefinitionQuery} from './types';
import {Page} from '@/types/base';
import {WorkflowCategory} from './types'; // Add this line

const DEFINITION_URL = '/api/v1/workflow/definition';
const INSTANCE_URL = '/api/v1/workflow/instance';

export const getDefinitions = (params?: WorkflowDefinitionQuery) =>
    request.get<Page<WorkflowDefinition>>(`${DEFINITION_URL}/page`, {params});

export const getDefinitionDetail = (id: number) =>
    request.get<WorkflowDefinition>(`${DEFINITION_URL}/${id}`);

export const getPublishedDefinitions = () =>
    request.get<WorkflowDefinition[]>(`${DEFINITION_URL}/published`);

export const deployDefinition = (id: number) =>
    request.post<void>(`${DEFINITION_URL}/${id}/deploy`);

export const deleteDefinition = (id: number) =>
    request.delete<void>(`${DEFINITION_URL}/${id}`);

export const saveDefinition = (data: WorkflowDefinition) =>
    request.post<WorkflowDefinition>(`${DEFINITION_URL}`, data);

export const updateDefinition = (id: number, data: WorkflowDefinition) =>
    request.put<WorkflowDefinition>(`${DEFINITION_URL}/${id}`, data);

/**
 * 发布工作流定义
 * @param id 工作流定义ID
 * @returns Promise<void>
 */
export const publishDefinition = (id: number) =>
    request.post<void>(`${DEFINITION_URL}/${id}/published`);

/**
 * 获取工作流分类列表
 * @returns Promise<WorkflowCategory[]> 工作流分类列表
 */
export const getWorkflowCategories = () =>
    request.get<WorkflowCategory[]>(`${DEFINITION_URL}/categories`);


/**
 * 启动工作流实例
 * @param processKey 流程定义key
 * @param categoryCode 分类编码
 * @returns Promise<void>
 */
export const startWorkflowInstance = (processKey: string, categoryCode: string) =>
    request.post<void>(`${INSTANCE_URL}/start`, {
        processKey,
        businessKey: `${categoryCode}_${Date.now()}`,
    });