#!/usr/bin/env ruby
# frozen_string_literal: true

require 'json'
require 'faraday'
require 'faraday_middleware'

GITHUB_ADDR = ENV['GITHUB_ADDR'].freeze
GITHUB_TOKEN = ENV['GITHUB_TOKEN'].freeze
PR = ENV['PULL_REQUEST_NUMBER'].freeze

module TwitchCPE
  module TeamCity
    class GitHub
      def initialize
        @addr = GITHUB_ADDR
        @token = GITHUB_TOKEN
        self
      end

      def server
        @server ||= Faraday.new(url: @addr) do |conn|
          conn.request :multipart
          conn.request :url_encoded
          conn.response :json, content_type: 'application/json'
          conn.adapter :net_http
          conn.headers = { 'Authorization' => "token #{@token}" }
        end
      end

      def pull_request_target(repo:, pr:)
        res = server.get("/api/v3/repos/#{repo}/pulls/#{pr}")
        return res.body['base']['ref'] if res.status == 200
        nil
      end
    end
  end
end

def teamcity_fail(message, details: nil, hard_fail: true)
  teamcity_status message
  puts "##teamcity[buildProblem description='#{message}']"
  abort details if !details.nil? && hard_fail
  exit if hard_fail
end

def teamcity_status(message)
  puts "##teamcity[buildStatus text='#{message}']"
end

def teamcity_success(message, details: nil, force_exit: false)
  puts "##teamcity[buildStatus status='SUCCESS' text='#{message}']"
  puts details unless details.nil?
  exit if force_exit
end

def teamcity_message(message)
  puts "##teamcity[message text='#{message}']"
end

def teamcity_parameter(key, value)
  puts "##teamcity[setParameter name='#{key}' value='#{value}']"
end

ghe = TwitchCPE::TeamCity::GitHub.new
pull_request_target = ghe.pull_request_target(repo: 'twilight/twilight', pr: PR)

teamcity_fail "Unable to get base branch for pull request #{PR}" unless pull_request_target
teamcity_parameter('env.PULL_REQUEST_TARGET', pull_request_target)
