require 'rest-client'
require 'byebug'
require 'json'

def create_pr(source_branch, destination_branch, close_branch)
  url = "https://api.bitbucket.org/2.0/repositories/mariojorge/gerencial/pullrequests"
  payload = {
    "title" => source_branch,
    "description" => "",
    "source" => {
      "branch" => {
        "name" => source_branch
      }
    },
    "destination" => {
      "branch" => {
        "name" => destination_branch
      }
    },
    "close_source_branch" => close_branch
  }.to_json

  response = RestClient.post url, payload, {
    "Authorization" => "Bearer ATCTT3xFfGN0qUKn7BjmSK8c4Af69anlyGzwQIFm3J4Z5Wu_CHJmARNdelrbr-6J7ZfvAkwoGyewXj9U82_uLMzXad2jS9txLaKUpH9VQzpCD9OplDA3iKLvhNTFNThV6PkRbvz0yw9MTJKlI4rClRvbk36o_GY2uAYWk9drVLkYGvDWPz_NIZY=D4ECA2EA",
    "Content-Type" => "application/json"
  }

  if response.code == 201
    pr = JSON.parse(response.body)
    pr_link = pr["links"]["html"]["href"]
    puts "Pull request criado com sucesso!"
    puts "Link do pull request: #{pr_link}"
  else
    puts "Erro ao criar pull request: #{response.code} - #{response.body}"
  end
end

if ARGV.length > 0
  source_branch = ARGV[0]
else
  puts "Por favor, insira o nome da branch de origem"
  exit
end

puts "CRIANDO PR PARA AMBIENTE DE TESTES"
create_pr(source_branch, 'ambiente_de_testes', false)
puts "CRIANDO PR PARA DESENVOLVIMENTO"
create_pr(source_branch, 'desenvolvimento', true)

# git push origin BRANCH && ./criar_pr.sh