const GITHUB_API = 'https://api.github.com';
async function ghFetch(path, token, options = {}) {
    return fetch(`${GITHUB_API}${path}`, {
        ...options,
        headers: {
            Authorization: `token ${token}`,
            Accept: 'application/vnd.github.v3+json',
            'Content-Type': 'application/json',
            ...options.headers,
        },
    });
}
const SAFE_NAME = /^[a-zA-Z0-9._-]+$/;
const SAFE_VERSION = /^\d+\.\d+\.\d+(-[\w.]+)?$/;
/** Create a GitHub Pull Request that bumps Actuate CMS package versions. */
export async function createUpgradePR(options) {
    const { owner, repo, githubToken, targetVersion, changesDescription } = options;
    if (!SAFE_NAME.test(owner))
        throw new Error('Invalid repository owner');
    if (!SAFE_NAME.test(repo))
        throw new Error('Invalid repository name');
    if (!SAFE_VERSION.test(targetVersion))
        throw new Error('Invalid version format');
    const baseBranch = options.baseBranch ?? 'main';
    const branchName = `actuate/upgrade-${targetVersion}`;
    // 1. Get the latest commit SHA on the base branch
    const refRes = await ghFetch(`/repos/${owner}/${repo}/git/ref/heads/${baseBranch}`, githubToken);
    if (!refRes.ok) {
        throw new Error(`Failed to get base branch: ${refRes.status} ${await refRes.text()}`);
    }
    const refData = (await refRes.json());
    const baseSha = refData.object.sha;
    // 2. Get the current package.json from the base branch
    const pkgRes = await ghFetch(`/repos/${owner}/${repo}/contents/package.json?ref=${baseBranch}`, githubToken);
    if (!pkgRes.ok) {
        throw new Error(`Failed to read package.json: ${pkgRes.status}`);
    }
    const pkgData = (await pkgRes.json());
    const pkgContent = atob(pkgData.content.replace(/\n/g, ''));
    const pkg = JSON.parse(pkgContent);
    // 3. Bump @actuate-media/* dependencies to the target version
    const actuatePackages = [
        '@actuate-media/cms-core',
        '@actuate-media/cms-admin',
        '@actuate-media/plugin-seo',
        '@actuate-media/plugin-forms',
        '@actuate-media/plugin-media',
        '@actuate-media/plugin-email',
        '@actuate-media/plugin-blocks',
        '@actuate-media/plugin-redirects',
        '@actuate-media/plugin-navigation',
        '@actuate-media/plugin-commerce',
        '@actuate-media/plugin-ai',
    ];
    for (const dep of actuatePackages) {
        if (pkg.dependencies?.[dep]) {
            pkg.dependencies[dep] = `^${targetVersion}`;
        }
        if (pkg.devDependencies?.[dep]) {
            pkg.devDependencies[dep] = `^${targetVersion}`;
        }
    }
    const updatedPkg = JSON.stringify(pkg, null, 2) + '\n';
    const encodedContent = btoa(updatedPkg);
    // 4. Create a new branch from the base
    const createBranchRes = await ghFetch(`/repos/${owner}/${repo}/git/refs`, githubToken, {
        method: 'POST',
        body: JSON.stringify({
            ref: `refs/heads/${branchName}`,
            sha: baseSha,
        }),
    });
    if (!createBranchRes.ok) {
        const errText = await createBranchRes.text();
        if (!errText.includes('Reference already exists')) {
            throw new Error(`Failed to create branch: ${createBranchRes.status} ${errText}`);
        }
    }
    // 5. Update package.json on the new branch
    const updateFileRes = await ghFetch(`/repos/${owner}/${repo}/contents/package.json`, githubToken, {
        method: 'PUT',
        body: JSON.stringify({
            message: `chore: bump Actuate CMS to ${targetVersion}`,
            content: encodedContent,
            sha: pkgData.sha,
            branch: branchName,
        }),
    });
    if (!updateFileRes.ok) {
        throw new Error(`Failed to update package.json: ${updateFileRes.status} ${await updateFileRes.text()}`);
    }
    // 6. Create the pull request
    const title = `chore: upgrade Actuate CMS to ${targetVersion}`;
    const body = [
        `## Actuate CMS Upgrade to ${targetVersion}`,
        '',
        changesDescription,
        '',
        '### After merging',
        '',
        '```bash',
        'npm install',
        'npx prisma migrate deploy',
        '```',
        '',
        '---',
        '*This PR was automatically created by the Actuate CMS admin panel.*',
    ].join('\n');
    const prRes = await ghFetch(`/repos/${owner}/${repo}/pulls`, githubToken, {
        method: 'POST',
        body: JSON.stringify({
            title,
            body,
            head: branchName,
            base: baseBranch,
        }),
    });
    if (!prRes.ok) {
        throw new Error(`Failed to create PR: ${prRes.status} ${await prRes.text()}`);
    }
    const pr = (await prRes.json());
    return {
        prNumber: pr.number,
        prUrl: pr.html_url,
        branchName,
    };
}
//# sourceMappingURL=upgrade-pr.js.map