# frozen_string_literal: true

require_relative "base"

module Neetob
  class CLI
    module Github
      class ProtectBranch < Base
        attr_accessor :branch_name, :required_rules_json_file_path, :repos, :repos_integrated_with_semaphore, :sandbox

        def initialize(branch_name, repos, required_rules_json_file_path = "", sandbox = false)
          super()
          @branch_name = branch_name
          @required_rules_json_file_path = required_rules_json_file_path
          @repos = repos
          @sandbox = sandbox
          @repos_integrated_with_semaphore = build_repos_integrated_with_semaphore_list.compact
        end

        def run
          matching_repos = find_all_matching_apps_or_repos(repos, :github, sandbox)
          inform_about_default_rules_file
          matching_repos.each do |repo|
            ui.info("\n Working on \"#{repo}\" repo")
            ui.info(" Updating \"#{branch_name}\" branch protection rules")
            has_semaphore_integrated = repos_integrated_with_semaphore.include?(repo)
            rules = read_json_file(required_rules_json_file_path || default_rules_file_path)
            rules.dig("required_status_checks", "contexts")&.clear if !has_semaphore_integrated
            rules_with_symbol_keys = rules.transform_keys(&:to_sym)
            client.protect_branch(repo, branch_name, rules_with_symbol_keys)
            ui.success("Branch protection rules updated successfully")
          end
        end

        private

          def default_rules_file_path
            File.expand_path("../../../../data/branch-protection-rules.json", __dir__)
          end

          def inform_about_default_rules_file
            if required_rules_json_file_path.nil?
              ui.info("Updating protection rules from the \"neetob/data/branch-protection-rules.json\" file")
            end
          end

          def build_repos_integrated_with_semaphore_list
            all_repos = NeetoCompliance::NeetoRepos.repos.values.flatten
            all_repos.map! do |repo_config|
              repo_config.is_a?(Hash) ? repo_config.to_a.map { |values| { values[0] => values[1] } } : repo_config
            end
            all_repos.flatten.map { |repo| (repo.is_a?(Hash) && repo.values[0].dig("semaphore")) ? "bigbinary/#{repo.keys[0]}" : nil }
          end
      end
    end
  end
end