require_relative '../helpers/git'

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

        other_action.ensure_git_status_clean

        if Git.current_branch != "main" && pr_number
          UI.message("Rebase pull request branch against main...")
          Actions.sh("git fetch origin main", log: true)
          Actions.sh("git rebase origin/main", log: true)
          UI.success("✅ Successfully rebased pull request branch against main")
        end

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

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

        actions_performed
      end

      def self.description
        "Push local commits from subtrees to source repos"
      end

      def self.authors
        ["Suno"]
      end

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

      def self.details
        "Pushes local commits from subtrees to upstream repositories and creates/updates PRs"
      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
