import request from '@/utils/request';
import type {
    RepositoryGroupResponse,
    RepositoryGroupQuery,
    RepositoryProjectResponse,
    RepositoryBranchResponse,
} from './types';
import { getExternalSystems } from '@/pages/Resource/External/List/service';
import { SystemType } from '@/pages/Resource/External/List/types';
import type { Page } from '@/types/base';

// API 基础路径
const GROUP_URL = '/api/v1/repository-group';
const PROJECT_URL = '/api/v1/repository-project';
const BRANCH_URL = '/api/v1/repository-branch';

// ==================== Git 实例 ====================

/**
 * 获取 Git 实例列表
 */
export const getGitInstances = () =>
    getExternalSystems({
        type: SystemType.GIT,
        enabled: true,
    }).then((response) => response.content);

// ==================== 仓库组 ====================

/**
 * 获取仓库组列表
 */
export const getRepositoryGroups = (params?: RepositoryGroupQuery) =>
    request.get<RepositoryGroupResponse[]>(`${GROUP_URL}/list`, { params });

/**
 * 同步仓库组数据
 */
export const syncRepositoryGroups = (externalSystemId: number) =>
    request.post<void>(`${GROUP_URL}/sync`, null, {
        params: { externalSystemId },
    });

// ==================== 仓库项目 ====================

/**
 * 获取仓库项目列表（分页）
 */
export const getRepositoryProjects = (params: {
    externalSystemId: number;
    repoGroupId?: number;
    pageNum?: number;
    size?: number;
}) =>
    request.get<Page<RepositoryProjectResponse>>(`${PROJECT_URL}/page`, {
        params: {
            pageNum: (params.pageNum ?? 1) - 1,
            size: params.size ?? 20,
            externalSystemId: params.externalSystemId,
            repoGroupId: params.repoGroupId,
        },
    });

/**
 * 获取仓库项目列表（不分页）
 */
export const getRepositoryProjectsList = (params: {
    externalSystemId: number;
    repoGroupId?: number;
}) =>
    request.get<RepositoryProjectResponse[]>(`${PROJECT_URL}/list`, {
        params,
    });

/**
 * 同步仓库项目数据
 * @param externalSystemId 外部系统ID（必填）
 * @param repoGroupId 仓库组ID（可选）不传=全量同步，传值=只同步该组
 */
export const syncRepositoryProjects = (externalSystemId: number, repoGroupId?: number) =>
    request.post<void>(`${PROJECT_URL}/sync`, null, {
        params: { externalSystemId, repoGroupId },
    });

// ==================== 仓库分支 ====================

/**
 * 获取仓库分支列表（分页，按最后更新时间倒序排序）
 */
export const getRepositoryBranches = (params: {
    externalSystemId: number;
    repoProjectId?: number;
    pageNum?: number;
    size?: number;
}) =>
    request.get<Page<RepositoryBranchResponse>>(`${BRANCH_URL}/page`, {
        params: {
            pageNum: (params.pageNum ?? 1) - 1,
            size: params.size ?? 20,
            sortField: 'lastUpdateTime',
            sortOrder: 'desc',
            externalSystemId: params.externalSystemId,
            repoProjectId: params.repoProjectId,
        },
    });

/**
 * 获取仓库分支列表（不分页）
 */
export const getRepositoryBranchesList = (params: {
    externalSystemId: number;
    repoProjectId: number;
}) =>
    request.get<RepositoryBranchResponse[]>(`${BRANCH_URL}/list`, {
        params,
    });

/**
 * 同步仓库分支数据
 * @param externalSystemId 外部系统ID（必填）
 * @param repoProjectId 项目ID（可选）不传=按repoGroupId规则，传值=只同步该项目（传此参数时repoGroupId必传）
 * @param repoGroupId 仓库组ID（可选）不传=全量同步，传值=同步该组所有项目的分支
 */
export const syncRepositoryBranches = (
    externalSystemId: number,
    repoProjectId?: number,
    repoGroupId?: number
) =>
    request.post<void>(`${BRANCH_URL}/sync`, null, {
        params: { externalSystemId, repoProjectId, repoGroupId },
    });

// ==================== 批量操作 ====================

/**
 * 同步所有数据（全量同步，不指定仓库组和项目）
 */
export const syncAllGitData = (externalSystemId: number) =>
    Promise.all([
        syncRepositoryGroups(externalSystemId),
        syncRepositoryProjects(externalSystemId),
        syncRepositoryBranches(externalSystemId),
    ]);
