name: Create JIRA tickets

on:
  issues:
    types: [opened, reopened]

  pull_request:
    types: [opened]

jobs:
  create_ticket_from_issue:
    name: Create JIRA ticket
    runs-on: ubuntu-latest
    steps:
      - name: Login
        uses: atlassian/gajira-login@master
        env:
          JIRA_BASE_URL: ${{ secrets.JIRA_BASE_URL }}
          JIRA_USER_EMAIL: ${{ secrets.JIRA_USER_EMAIL }}
          JIRA_API_TOKEN: ${{ secrets.JIRA_API_TOKEN }}

      - name: Set event vars
        id: event
        run: |
          if [ ${{github.event.issue}} ]; then 
            echo "::set-output name=SUMMARY::GITHUB ISSUE #${{github.event.issue.number}} ${{github.event.issue.title}}"
            echo "::set-output name=DESC::${{github.event.issue.html_url}} \n\n ${{github.event.issue.body}}"
            echo "::set-output name=ISSUE_TYPE::Bug"
            echo "::set-output name=LABEL::issue"
            echo "::set-output name=USER::${{github.event.issue.user.login}}"
          elif [ ${{github.event.pull_request}} ]; then 
            echo "::set-output name=SUMMARY::PR #${{github.event.pull_request.number}} ${{github.event.pull_request.title}}"
            echo "::set-output name=DESC::${{github.event.pull_request.html_url}} \n\n ${{github.event.pull_request.body}}"
            echo "::set-output name=ISSUE_TYPE::Task"
            echo "::set-output name=LABEL::pr"
            echo "::set-output name=USER::${{github.event.pull_request.user.login}}"
          fi
      - name: Debug event
        run: |
          echo "SUMMARY ${{steps.event.outputs.SUMMARY}}"
          echo "DESC ${{steps.event.outputs.DESC}}"

      - name: Create ticket
        id: create
        uses: atlassian/gajira-create@master
        with:
          project: LABS
          issuetype: ${{steps.event.outputs.ISSUE_TYPE}}
          summary: ${{steps.event.outputs.SUMMARY}}
          description: ${{steps.event.outputs.DESC}}
          fields: '{"labels": ["github", "${{steps.event.outputs.LABEL}}"], "customfield_10135": "serverless-fauna"}'

      - name: Set triage state
        if: ${{ steps.create.outputs.issue }}
        uses: atlassian/gajira-transition@master
        with:
          issue: ${{ steps.create.outputs.issue }}
          transition: "TRIAGE"

      - name: Create comment
        if: ${{ github.event.issue }}
        uses: peter-evans/create-or-update-comment@v1
        with:
          issue-number: ${{github.event.issue.number}}
          body: Internal ticket number is ${{steps.create.outputs.issue}}

      - name: Created issue
        if: ${{ steps.create.outputs.issue }}
        run: echo "Issue ${{ steps.create.outputs.issue }} was created"
