name: Dependency Check

on:
  schedule:
    - cron: '0 9 * * 1'  # каждый понедельник 09:00 UTC
  workflow_dispatch:

permissions:
  contents: read
  issues: write

jobs:
  npm-outdated:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install root deps
        run: npm install --ignore-scripts

      - name: Check outdated (root)
        id: root_outdated
        run: |
          npm outdated --json > root-outdated.json || true
          if [ "$(cat root-outdated.json)" != "{}" ]; then
            echo "has_updates=true" >> "$GITHUB_OUTPUT"
          fi

      - name: Install app deps
        working-directory: app
        run: npm install --ignore-scripts

      - name: Check outdated (app)
        id: app_outdated
        working-directory: app
        run: |
          npm outdated --json > app-outdated.json || true
          if [ "$(cat app-outdated.json)" != "{}" ]; then
            echo "has_updates=true" >> "$GITHUB_OUTPUT"
          fi

      - name: Open issue if outdated
        if: steps.root_outdated.outputs.has_updates == 'true' || steps.app_outdated.outputs.has_updates == 'true'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          {
            echo "## Weekly outdated dependencies — $(date -u +"%Y-%m-%d")"
            echo
            echo "### Root (package.json)"
            echo '```json'
            cat root-outdated.json
            echo '```'
            echo
            echo "### App (app/package.json)"
            echo '```json'
            cat app/app-outdated.json
            echo '```'
          } > issue-body.md
          gh issue create --title "Weekly outdated check $(date -u +"%Y-%m-%d")" --body-file issue-body.md --label dependencies
