import { createAppAuth } from '@octokit/auth-app';
import { Octokit } from '@octokit/rest';

import { env } from './env';

export const getInstallationToken = async (installationId: string) => {
  const auth = createAppAuth({
    appId: env.githubAppId,
    privateKey: env.githubPrivateKey,
    installationId,
  });
  const result = await auth({ type: 'installation' });
  return result.token;
};

export const getInstallationOctokit = (installationId: string) =>
  new Octokit({
    authStrategy: createAppAuth,
    auth: {
      appId: env.githubAppId,
      privateKey: env.githubPrivateKey,
      installationId,
    },
    userAgent: 'Spoon Agent Worker',
    request: {
      headers: {
        'X-GitHub-Api-Version': '2022-11-28',
      },
    },
  });

export const openDraftPullRequest = async (args: {
  installationId: string;
  forkOwner: string;
  forkRepo: string;
  baseBranch: string;
  workBranch: string;
  title: string;
  body: string;
}) => {
  const octokit = getInstallationOctokit(args.installationId);
  const result = await octokit.rest.pulls.create({
    owner: args.forkOwner,
    repo: args.forkRepo,
    base: args.baseBranch,
    head: args.workBranch,
    title: args.title,
    body: args.body,
    draft: true,
  });
  return result.data;
};
