name: Repo / Auto-apply milestone

on:
  pull_request_target:
    types:
      - opened
      - reopened

jobs:
  milestone:
    name: Apply milestone
    runs-on: ubuntu-22.04
    if: ${{ contains(github.repository_owner, 'jellyfin') }}
    steps:
      - uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
        with:
          github-token: ${{ secrets.JF_BOT_TOKEN }}
          script: |
            const owner = context.repo.owner;
            const repo = context.repo.repo;
            const pr_id = context.issue.number;

            let response = await github.rest.issues.get({
              owner,
              repo,
              issue_number: pr_id,
            });
            const pr = response.data;

            if (pr.milestone !== null) {
              return;
            }

            response = await github.rest.issues.listMilestones({
              owner,
              repo,
              state: 'open',
            });
            const milestones = response.data; 

            // Find first open milestone
            const milestone = milestones.reduce(
              (prev, current) => prev?.number < current.number ? prev : current, 
              null,
            );

            if (milestone === null) {
              console.warn('No suitable milestone found, aborting.');
              return;
            }

            console.log(`Found milestone to apply: ${milestone.title}`);

            await github.rest.issues.update({
              owner,
              repo,
              issue_number: pr_id,
              milestone: milestone.number,
            });

            console.log(`Successfully applied milestone ${milestone.title} to PR #${pr_id}`);
