name: Pull request test resource link

on:
  workflow_run:
    workflows:
      - CI
    types:
      - completed

permissions:
  actions: read
  contents: read
  pull-requests: write

jobs:
  comment:
    name: Link test resource
    if: github.event.workflow_run.event == 'pull_request'
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - name: Create or update pull request comment
        uses: actions/github-script@v9
        with:
          script: |
            const marker = '<!-- sky-phone-test-resource -->';
            const run = context.payload.workflow_run;
            const pullRequest = run.pull_requests?.[0];

            if (!pullRequest) {
              core.notice('The CI run is not associated with a pull request.');
              return;
            }

            const { owner, repo } = context.repo;
            const runUrl = `https://github.com/${owner}/${repo}/actions/runs/${run.id}`;
            let body;

            if (run.conclusion === 'success') {
              const response = await github.rest.actions.listWorkflowRunArtifacts({
                owner,
                repo,
                run_id: run.id,
                per_page: 100,
              });
              const prefix = `sky_phone-pr-${pullRequest.number}-`;
              const artifact = response.data.artifacts.find(
                (candidate) =>
                  !candidate.expired &&
                  candidate.name.startsWith(prefix) &&
                  /^sky_phone-pr-\d+-[0-9a-f]{40}\.zip$/.test(candidate.name),
              );

              if (!artifact) {
                core.setFailed('CI succeeded without a pull request test resource artifact.');
                return;
              }

              const artifactUrl = `https://github.com/${owner}/${repo}/actions/runs/${run.id}/artifacts/${artifact.id}`;
              body = [
                marker,
                '## Sky Phone Test-Resource',
                '',
                `✅ Der aktuelle Pull Request wurde erfolgreich geprüft und gebaut. [Test-Resource herunterladen](${artifactUrl}).`,
                '',
                'Das ZIP enthält den deploybaren `sky_phone`-Ordner inklusive gebautem Frontend und bleibt 14 Tage verfügbar.',
                '',
                `[Workflow-Lauf öffnen](${runUrl})`,
              ].join('\n');
            } else {
              body = [
                marker,
                '## Sky Phone Test-Resource',
                '',
                `❌ Für den aktuellen Stand wurde keine freigegebene Test-Resource erzeugt, weil der [CI-Lauf](${runUrl}) nicht erfolgreich war.`,
              ].join('\n');
            }

            const comments = await github.paginate(github.rest.issues.listComments, {
              owner,
              repo,
              issue_number: pullRequest.number,
              per_page: 100,
            });
            const existing = comments.find(
              (comment) => comment.user?.type === 'Bot' && comment.body?.includes(marker),
            );

            if (existing) {
              await github.rest.issues.updateComment({
                owner,
                repo,
                comment_id: existing.id,
                body,
              });
            } else {
              await github.rest.issues.createComment({
                owner,
                repo,
                issue_number: pullRequest.number,
                body,
              });
            }
