import request from '@/utils/request';
import type { JenkinsViewDTO, JenkinsJobDTO, JenkinsBuildDTO } from './types';
import { getExternalSystems } from '@/pages/Resource/External/List/service';
import { SystemType } from '@/pages/Resource/External/List/types';
import type { Page } from '@/types/base';

// 获取 Jenkins 实例列表
export const getJenkinsInstances = () => 
  getExternalSystems({
    type: SystemType.JENKINS,
    enabled: true
  }).then(response => response.content);

// ==================== Jenkins 视图 ====================

// 获取视图列表
export const getJenkinsViews = (externalSystemId: number) =>
  request.get<JenkinsViewDTO[]>(`/api/v1/jenkins-view/list`, {
    params: { externalSystemId }
  });

// 同步视图
export const syncJenkinsViews = (externalSystemId: number) =>
  request.post<void>(`/api/v1/jenkins-view/sync`, null, {
    params: { externalSystemId }
  });

// ==================== Jenkins 任务 ====================

// 获取任务列表（分页）
export const getJenkinsJobs = (params: { 
  externalSystemId: number; 
  viewId?: number;
  pageNum?: number;
  size?: number;
}) =>
  request.get<Page<JenkinsJobDTO>>(`/api/v1/jenkins-job/page`, { 
    params: {
      pageNum: (params.pageNum ?? 1) - 1,
      size: params.size ?? 20,
      externalSystemId: params.externalSystemId,
      viewId: params.viewId
    }
  });

// 同步任务
export const syncJenkinsJobs = (params: { externalSystemId: number; viewId?: number }) =>
  request.post<void>(`/api/v1/jenkins-job/sync`, null, { params });

// ==================== Jenkins 构建 ====================

// 获取构建列表（分页，按开始时间倒序排序）
export const getJenkinsBuilds = (params: { 
  externalSystemId: number; 
  jobId?: number;
  pageNum?: number;
  size?: number;
}) =>
  request.get<Page<JenkinsBuildDTO>>(`/api/v1/jenkins-build/page`, { 
    params: {
      pageNum: (params.pageNum ?? 1) - 1,
      size: params.size ?? 20,
      sortField: 'starttime',
      sortOrder: 'desc',
      externalSystemId: params.externalSystemId,
      jobId: params.jobId
    }
  });

// 同步构建（根据jobId）
export const syncJenkinsBuilds = (params: { externalSystemId: number; jobId?: number }) =>
  request.post<void>(`/api/v1/jenkins-build/sync`, null, { params });
