import { logger } from "../logger/index.mjs";
import { checkPipelineFileExists } from "./bitbucket.service.mjs";
import { checkWorkflowFileExists, createWorkflowFile } from "./github.service.mjs";
import { checkPipelineFileExists as checkPipelineFileExists$1, createPipelineFile } from "./gitlab.service.mjs";

//#region src/services/ci.service.ts
const GITHUB_WORKFLOW_FILENAME = ".github/workflows/intlayer-cms.yml";
const GITLAB_PIPELINE_FILENAME = ".gitlab-ci.yml";
const BITBUCKET_PIPELINE_FILENAME = "bitbucket-pipelines.yml";
const GITHUB_TEMPLATE = `name: Intlayer CMS Update
on:
  repository_dispatch:
    types: [intlayer_cms_update]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: npm run build
`;
const GITLAB_TEMPLATE = `stages:
  - build

intlayer_cms_update:
  stage: build
  only:
    - triggers
  script:
    - npm ci
    - npm run build
`;
const BITBUCKET_TEMPLATE = `pipelines:
  custom:
    intlayer-cms-update:
      - step:
          name: Build
          script:
            - npm ci
            - npm run build
`;
/**
* Get access token from project's OAuth2 access
*/
const getAccessToken = (project) => {
	return (project.oAuth2Access?.[0])?.accessToken?.[0] || null;
};
/**
* Get CI configuration status for a project
*/
const getCIStatus = async (project) => {
	const { repository } = project;
	if (!repository) throw new Error("Project is not connected to a repository.");
	const accessToken = getAccessToken(project);
	if (!accessToken) throw new Error("No valid OAuth2 access token found.");
	const branch = repository.branch || "main";
	try {
		switch (repository.provider) {
			case "github": {
				const { owner, repository: repoName } = repository;
				const filename = GITHUB_WORKFLOW_FILENAME;
				return {
					exists: await checkWorkflowFileExists(accessToken, owner, repoName, filename, branch),
					content: GITHUB_TEMPLATE,
					path: filename,
					fileUrl: `https://github.com/${owner}/${repoName}/blob/${branch}/${filename}`,
					allowAutoPush: true
				};
			}
			case "gitlab": {
				const { projectId, instanceUrl } = repository;
				if (!projectId) throw new Error("GitLab project ID is required.");
				const filename = GITLAB_PIPELINE_FILENAME;
				return {
					exists: await checkPipelineFileExists$1(accessToken, projectId, filename, branch, instanceUrl),
					content: GITLAB_TEMPLATE,
					path: filename,
					fileUrl: `${instanceUrl || "https://gitlab.com"}/${repository.owner}/${repository.repository}/-/blob/${branch}/${filename}`,
					allowAutoPush: true
				};
			}
			case "bitbucket": {
				const { workspace, repository: repoSlug } = repository;
				const filename = BITBUCKET_PIPELINE_FILENAME;
				return {
					exists: await checkPipelineFileExists(accessToken, workspace, repoSlug, filename, branch),
					content: BITBUCKET_TEMPLATE,
					path: filename,
					fileUrl: `https://bitbucket.org/${workspace}/${repoSlug}/src/${branch}/${filename}`,
					allowAutoPush: false
				};
			}
			default: throw new Error(`Unsupported repository provider: ${repository.provider}`);
		}
	} catch (error) {
		logger.error("Error getting CI status:", error);
		throw error;
	}
};
/**
* Install CI configuration file in the repository
*/
const installCI = async (project) => {
	const { repository } = project;
	if (!repository) throw new Error("Project is not connected to a repository.");
	const accessToken = getAccessToken(project);
	if (!accessToken) throw new Error("No valid OAuth2 access token found.");
	const branch = repository.branch || "main";
	try {
		switch (repository.provider) {
			case "github": {
				const { owner, repository: repoName } = repository;
				await createWorkflowFile(accessToken, owner, repoName, GITHUB_WORKFLOW_FILENAME, GITHUB_TEMPLATE, branch, "Add Intlayer CMS workflow");
				break;
			}
			case "gitlab": {
				const { projectId, instanceUrl } = repository;
				if (!projectId) throw new Error("GitLab project ID is required.");
				await createPipelineFile(accessToken, projectId, GITLAB_PIPELINE_FILENAME, GITLAB_TEMPLATE, branch, instanceUrl, "Add Intlayer CMS pipeline");
				break;
			}
			case "bitbucket": throw new Error("Bitbucket does not support automatic CI file installation. Please add the file manually.");
			default: throw new Error(`Unsupported repository provider: ${repository.provider}`);
		}
		logger.info(`Successfully installed CI configuration for project ${project.id}`);
	} catch (error) {
		logger.error("Error installing CI configuration:", error);
		throw error;
	}
};

//#endregion
export { BITBUCKET_PIPELINE_FILENAME, BITBUCKET_TEMPLATE, GITHUB_TEMPLATE, GITHUB_WORKFLOW_FILENAME, GITLAB_PIPELINE_FILENAME, GITLAB_TEMPLATE, getCIStatus, installCI };
//# sourceMappingURL=ci.service.mjs.map