name: OSS Weekend Issues

on:
  issues:
    types: [opened]

jobs:
  close-issues-during-weekend:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      issues: write
    steps:
      - name: Close new issues during OSS weekend
        uses: actions/github-script@v7
        with:
          script: |
            const issueAuthor = context.payload.issue.user.login;
            const defaultBranch = context.payload.repository.default_branch;

            if (issueAuthor.endsWith('[bot]') || issueAuthor === 'dependabot[bot]') {
              console.log(`Skipping bot: ${issueAuthor}`);
              return;
            }

            async function getPermission(username) {
              try {
                const { data: permissionLevel } = await github.rest.repos.getCollaboratorPermissionLevel({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  username,
                });
                return permissionLevel.permission;
              } catch {
                return null;
              }
            }

            async function getTextFile(path) {
              const { data: fileContent } = await github.rest.repos.getContent({
                owner: context.repo.owner,
                repo: context.repo.repo,
                path,
                ref: defaultBranch,
              });

              if (!('content' in fileContent) || typeof fileContent.content !== 'string') {
                throw new Error(`Expected file content for ${path}`);
              }

              return Buffer.from(fileContent.content, 'base64').toString('utf8');
            }

            const permission = await getPermission(issueAuthor);
            if (['admin', 'maintain', 'write'].includes(permission)) {
              console.log(`${issueAuthor} is a collaborator with ${permission} access`);
              return;
            }

            let weekendState;
            try {
              weekendState = JSON.parse(await getTextFile('.github/oss-weekend.json'));
            } catch (error) {
              if (error && typeof error === 'object' && 'status' in error && error.status === 404) {
                console.log('OSS weekend is not active');
                return;
              }
              throw error;
            }

            if (!weekendState?.active) {
              console.log('OSS weekend is not active');
              return;
            }

            const reopenDate = weekendState.reopensOnText || weekendState.reopensOn || 'after the weekend';
            const discordUrl = weekendState.discordUrl || 'https://discord.com/invite/3cU7Bz4UPx';
            const message = [
              `Hi @${issueAuthor}, thanks for opening an issue.`,
              '',
              `OSS weekend is active until ${reopenDate}, so new issues are being auto-closed for now.`,
              '',
              `Please reopen or submit this issue again after ${reopenDate}. For support, join [Discord](${discordUrl}).`,
            ].join('\n');

            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: message,
            });

            await github.rest.issues.update({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              state: 'closed',
            });
