module Fastlane
  module Actions
    class TestflightCredentialsAction < Action
      def self.run(params)
        key_content = params[:app_store_connect_api_key]
        issuer_id = params[:app_store_connect_api_issuer_id]
        key_id = params[:app_store_connect_api_key_id]

        is_key_content_base64 = begin
          # parse to validate JSON
          JSON.parse(key_content)
          false
        rescue
          true
        end

        # decode from base64
        other_action.app_store_connect_api_key(
          is_key_content_base64: is_key_content_base64,
          key_content: key_content,
          issuer_id: issuer_id,
          key_id: key_id
        )
      end

      def self.description
        "Returns the App Store Connect API Key JSON key data"
      end

      def self.return_value
        "App Store Connect API Key as a JSON string"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :app_store_connect_api_key_id,
            description: "The App Store Connect API Key ID",
            env_name: "APP_STORE_CONNECT_API_KEY_KEY_ID",
            verify_block: proc do |value|
              if value.empty?
                UI.user_error!("APP_STORE_CONNECT_API_KEY_KEY_ID is not set")
              end
            end),
          FastlaneCore::ConfigItem.new(key: :app_store_connect_api_issuer_id,
            description: "The App Store Connect API Issuer ID",
            env_name: "APP_STORE_CONNECT_API_KEY_ISSUER_ID",
            verify_block: proc do |value|
              if value.empty?
                UI.user_error!("APP_STORE_CONNECT_API_KEY_ISSUER_ID is not set")
              end
            end),
          FastlaneCore::ConfigItem.new(key: :app_store_connect_api_key,
            description: "The App Store Connect API Key (JSON string or base64-encoded)",
            env_name: "APP_STORE_CONNECT_API_KEY_KEY",
            verify_block: proc do |value|
              if value.empty?
                UI.user_error!("APPSTORE_CONNECT_API_KEY_KEY is not set")
              end
            end),
        ]
      end

      def self.authors
        ["Suno"]
      end

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