require_relative '../helpers/git'

module Fastlane
  module Actions
    class SubtreesPullAction < Action
      def self.run(params)
        pr_number = params[:pr_number]

        other_action.ensure_git_status_clean

        actions_performed = other_action.subtrees_config.map do |subtree, config|
          other_action.subtree_pull(
            subtree: subtree,
            repo: config["repo"],
            branch: config["branch"],
            pr_number: pr_number
          )
        end.flatten

        if actions_performed.count > 0 && Git.current_branch === "main"
          UI.message("Pushing new commits from all subtrees to main branch...")
          Actions.sh("git push origin main", log: true)
          UI.success("✅ Successfully pushed new commits from all subtrees to main branch")
          actions_performed << "✅ Pushed new commits from all subtrees to main branch"
        end

        other_action.subtrees_status(pr_number: pr_number, actions_performed: actions_performed)

        actions_performed
      end

      def self.description
        "Pull new commits from source repos into subtrees"
      end

      def self.authors
        ["Suno"]
      end

      def self.return_value
        "Array of actions performed during the pull operation"
      end

      def self.details
        "Pulls latest changes from all configured subtree repositories and pushes to main if on main branch"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(
            key: :pr_number,
            description: "PR number from mobile repo to sync (defaults to GITHUB environment if available)",
            type: String,
            optional: true,
            verify_block: proc do |value|
              UI.user_error!(':pr_number option cannot be empty') if value.to_s.empty?
            end
          ),
        ]
      end

      def self.is_supported?(platform)
        true
      end
    end
  end
end
