module Fastlane
  module Actions
    class PlaystoreCredentialsAction < Action
      def self.run(params)
        # parse to validate JSON
        JSON.parse(params[:playstore_key])
        # return as is
        params[:playstore_key]
      rescue
        # decode from base64
        Base64.decode64(params[:playstore_key])
      end

      def self.description
        "Returns the Play Store Service Credentials JSON key data"
      end

      def self.return_value
        "Play Store Service Credentials as a JSON string"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :playstore_key,
            description: "The Play Store Upload JSON key (JSON string or base64-encoded)",
            env_name: "PLAYSTORE_SERVICE_ACCOUNT_JSON_BASE64",
            verify_block: proc do |value|
              if value.empty?
                UI.user_error!("PLAYSTORE_SERVICE_ACCOUNT_JSON_BASE64 is not set")
              end
            end)
        ]
      end

      def self.authors
        ["Suno"]
      end

      def self.is_supported?(platform)
        platform == :android
      end
    end
  end
end
