import request from '@/utils/request';
import type { BaseResponse } from '@/types/api';
import type { JenkinsDTO, JenkinsQuery, TestConnectionDTO, JenkinsSyncHistoryDTO, JenkinsViewDTO, JenkinsJobDTO, JenkinsBuildDTO } from './types';

export const getJenkinsList = async (params?: JenkinsQuery) => {
  return await request.get<BaseResponse<JenkinsDTO[]>>('/api/system/jenkins', { params });
};

export const createJenkins = async (data: Partial<JenkinsDTO>): ApiResponse<JenkinsDTO> => {
  return await request.post('/api/system/jenkins', data);
};

export const updateJenkins = async (id: number, data: Partial<JenkinsDTO>): ApiResponse<JenkinsDTO> => {
  return await request.put(`/api/system/jenkins/${id}`, data);
};

export const deleteJenkins = async (id: number): ApiResponse<void> => {
  return await request.delete(`/api/system/jenkins/${id}`);
};

export const testConnection = async (data: TestConnectionDTO): ApiResponse<boolean> => {
  return await request.post('/api/system/jenkins/test-connection', data);
};

export const syncAll = async (id: number): ApiResponse<number> => {
  return await request.post(`/api/system/jenkins/${id}/sync/all`);
};

export const getSyncHistories = async () => {
  return await request.get<BaseResponse<JenkinsSyncHistoryDTO[]>>('/api/system/jenkins/sync/histories');
};

export const sync = async (id: number, type: 'ALL' | 'VIEW' | 'JOB' | 'BUILD') => {
  return await request.post<BaseResponse<number>>(`/api/system/jenkins/${id}/sync/${type.toLowerCase()}`);
};

export const getJenkinsViews = async (jenkinsId: number) => {
  return await request.get<BaseResponse<JenkinsViewDTO[]>>(`/api/system/jenkins/${jenkinsId}/views`);
};

export const getJenkinsJobs = async (jenkinsId: number) => {
  return await request.get<BaseResponse<JenkinsJobDTO[]>>(`/api/system/jenkins/${jenkinsId}/jobs`);
};

export const getJenkinsBuilds = async (jenkinsId: number, jobId: number) => {
  return await request.get<BaseResponse<JenkinsBuildDTO[]>>(`/api/system/jenkins/${jenkinsId}/jobs/${jobId}/builds`);
}; 