const fs = require('fs');

/**
 * Creates a GitHub pull request for gopls quickfixes
 * @param {Object} params - Parameters object
 * @param {Object} params.github - GitHub API client
 * @param {Object} params.context - GitHub Actions context
 * @param {Object} params.core - GitHub Actions core utilities
 * @param {Object} params.exec - GitHub Actions exec utilities
 * @param {string} params.issueNumber - The issue number to link to (optional)
 * @param {string} params.fixedFilesPath - Path to the fixed files list
 * @returns {Promise<number>} The created PR number
 */
module.exports = async ({ github, context, core, exec, issueNumber, fixedFilesPath }) => {
  try {
    const fixedFiles = fs.readFileSync(fixedFilesPath, 'utf8');

    // Configure git
    await exec.exec('git', ['config', '--local', 'user.email', 'action@github.com']);
    await exec.exec('git', ['config', '--local', 'user.name', 'github-actions[bot]']);

    // Create branch name
    const branchName = `gopls-quickfix-${new Date().toISOString().split('T')[0].replace(/-/g, '')}`;

    // Create and push branch
    await exec.exec('git', ['checkout', '-b', branchName]);
    await exec.exec('git', ['add', '.']);
    await exec.exec('git', ['commit', '-m', '🔧 Apply gopls quickfixes']);
    await exec.exec('git', ['push', 'origin', branchName]);

    // Create PR
    const prBody = `## 🔧 Gopls Quickfixes Applied

This PR applies automatic fixes suggested by gopls for code quality improvements.

> [!TIP]
> You might want to push an empty commit to this PR to trigger CI checks.

### Files Modified
\`\`\`
${fixedFiles}
\`\`\`

### Changes
- Applied gopls quickfixes to improve code quality
- All changes are automated and safe
- Generated by monthly gopls check workflow

### Related Issue
${issueNumber ? `Closes #${issueNumber}` : ''}

---
*This PR was automatically generated by the monthly gopls quickfix workflow.*
`;

    const pr = await github.rest.pulls.create({
      owner: context.repo.owner,
      repo: context.repo.repo,
      title: `🔧 Apply gopls quickfixes - ${new Date().toISOString().split('T')[0]}`,
      body: prBody,
      head: branchName,
      base: 'main',
      labels: ['gopls', 'automated', 'maintenance']
    });

    const prNumber = pr.data.number;
    console.log(`Created PR #${prNumber}`);

    // Link PR to issue if issue was created
    if (issueNumber) {
      await github.rest.issues.createComment({
        owner: context.repo.owner,
        repo: context.repo.repo,
        issue_number: parseInt(issueNumber),
        body: `🔗 **Pull Request Created**

A pull request has been created to address the gopls quickfix issues found in this issue.

**PR**: #${prNumber}
**Status**: Ready for review

The PR will automatically close this issue when merged.`
      });
    }

    return prNumber;
  } catch (error) {
    core.setFailed(`Failed to create pull request: ${error.message}`);
    throw error;
  }
};
