name: Create Branch File

on:
  create:
    branches:
      - 'committee/*'

jobs:
  create-file:
    runs-on: ubuntu-latest
    steps:
      - name: Get branch name
        id: branch_name
        run: |
          branch_name=${{ github.ref }}
          echo "branch=${branch_name#refs/heads/committee/}" >> $GITHUB_OUTPUT
      - name: Check out code
        uses: actions/checkout@v3
        with: 
          ref: committee/${{ steps.branch_name.outputs.branch }}

      - name: Generate Committee File
        run: |
          branch_name=${{ github.ref }}
          branch_name=${branch_name#refs/heads/committee/}
          sed "s/class Example/class ${branch_name^}/g" src/Committees/example.py > "src/Committees/${branch_name}.py"
        shell: bash

      - name: Commit and Push Changes
        run: |
          branch_name=${{ github.ref }}
          branch_name=${branch_name#refs/heads/committee/}
          git config --global user.email "actions@github.com"
          git config --global user.name "GitHub Actions"
          git status
          git add "src/Committees/${branch_name}.py"
          git commit -m "Add ${branch_name}.py"
          git push origin committee/$branch_name
        shell: bash

      - name: Create Committee Team
        id: create_team
        env:
          GITHUB_TOKEN: ${{ secrets.ORG_ADMIN }}
        run: |
          branch_name=${{ github.ref }}
          branch_name=${branch_name#refs/heads/committee/}
          response=$(curl -X POST \
            -H "Accept: application/vnd.github+json" \
            -H "Authorization: Bearer $GITHUB_TOKEN" \
            https://api.github.com/orgs/BX-bot-ecosystem/teams \
            -d '{"name":"'$branch_name'","privacy":"closed"}')
          echo $response
          team_id=$(echo "$response" | jq -r '.id')
          echo "Team ID: $team_id"
          echo "team_id=$team_id" >> $GITHUB_OUTPUT

      - name: Protect Branch
        env:
          GITHUB_TOKEN: ${{ secrets.ORG_ADMIN }}
        run: |
          branch_name=${{ github.ref }}
          branch_name=${branch_name#refs/heads/committee/}
          team_id=${{ steps.create_team.outputs.team_id }}
          response=$(curl -X PUT \
            -H "Accept: application/vnd.github+json" \
            -H "Authorization: Bearer $GITHUB_TOKEN" \
            https://api.github.com/repos/BX-bot-ecosystem/Telegram-BX-Bot/branches/committee/$branch_name/protection \
            -d '{"required_status_checks": null, "enforce_admins": false, "required_pull_request_reviews": null, "restrictions": {"users": [], "teams": ['$team_id']}}')
          echo "Branch Protection Response: $response"
            
