# frozen_string_literal: true

require_relative "../base"

module Neetob
  class CLI
    module Github
      module MakePr
        class Base < Github::Base
          BRANCH_NAME = "neeto_compliance"
          PR_TITLE = "Neeto Compliance"
          attr_accessor :branch_name, :pr_title

          def initialize(pr_title = PR_TITLE, branch_name = BRANCH_NAME)
            super()
            @branch_name = branch_name || BRANCH_NAME
            @pr_title = pr_title || PR_TITLE
          end

          private

            def delete_and_create_temp_neetob_dir
              `rm -rf /tmp/neetob`
              `mkdir /tmp/neetob`
            end

            def app_name_without_org_suffix(app)
              app.split("/").last
            end

            def clone_app_in_tmp_dir(app)
              `git clone --quiet git@github.com:#{app}.git /tmp/neetob/#{app_name_without_org_suffix(app)}`
            end

            def add_commmit_and_push_changes(app)
              `#{cd_to_app_in_tmp_dir(app)} && git add . && git commit -m "#{pr_title}" && git push -u origin #{branch_name} --force`
            end

            def delete_local_feature_branch(app)
              `#{cd_to_app_in_tmp_dir(app)} && git checkout main && git branch -D #{branch_name}`
            end

            def checkout_to_new_branch(app)
              `#{cd_to_app_in_tmp_dir(app)} && git checkout -b #{branch_name}`
            end

            def checkout_to_feature_branch(app)
              `#{cd_to_app_in_tmp_dir(app)} && git checkout #{branch_name}`
            end

            def delete_remote_feature_branch(app)
              `#{cd_to_app_in_tmp_dir(app)} && git push origin --delete #{branch_name}`
            end

            def check_and_delete_remote_branch(app)
              checkout_to_feature_branch(app)
              if $?.success?
                ui.info("Remote branch found with the name \"#{branch_name}\"")
                delete_remote_feature_branch(app)
                delete_local_feature_branch(app)
              end
              checkout_to_new_branch(app)
            end

            def cd_to_app_in_tmp_dir(app)
              "cd /tmp/neetob/#{app_name_without_org_suffix(app)}"
            end
        end
      end
    end
  end
end