require_relative "../helpers/git"
require_relative "../helpers/config"

module Fastlane
  module Actions
    class SyncProfilesAction < Action
      def self.run(params)
        renew = params[:renew]
        is_ci = other_action.is_ci
        if is_ci && renew
          UI.user_error!("Refusing to renew profiles on CI")
        end

        testflight_credentials = other_action.testflight_credentials
        build_flavor = params[:build_flavor]
        build_type = params[:build_type]
        sync_devices = params[:sync_devices]
        build_config = BuildConfig.for(build_flavor)

        profile_type = case params[:build_type]
        when BuildType::RELEASE
          build_config[:export_method].gsub("-", "")
        when BuildType::DEBUG
          "development"
        end

        readonly = !sync_devices && !renew

        if sync_devices
          other_action.sync_devices
        end

        timestamp = Time.now.to_i

        build_config[:provisioning_profiles].keys.each do |app_identifier|
          profile_name = if renew
            # add suffix to allow automatic deduping in xcode
            "match #{build_config[:export_method].split("-").map(&:capitalize).join} #{app_identifier} #{timestamp}"
          else
            nil
          end
          other_action.sync_code_signing(
            # App-specific opts
            app_identifier: app_identifier,
            type: profile_type,
            profile_name: profile_name,
            # Common opts
            api_key: testflight_credentials,
            readonly: readonly,
            force: renew,
            force_for_new_certificates: renew,
            force_for_new_devices: sync_devices,
            fail_on_name_taken: renew,
          )

          UI.message("#{lane_context[SharedValues::MATCH_PROVISIONING_PROFILE_MAPPING]}")
        end
      end

      #####################################################
      # @!group Documentation
      #####################################################

      def self.description
        "Sync code signing certificates for iOS"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(
            key: :build_type,
            description: "The build type (#{BuildType::ALL.join(', ')})",
            verify_block: proc do |value|
              UI.user_error!("Invalid build type (must be one of #{BuildType::ALL.join(', ')})") unless BuildType::ALL.include?(value)
            end,
          ),
          FastlaneCore::ConfigItem.new(
            key: :build_flavor,
            description: "The build flavor (#{BuildFlavor::ALL.join(', ')})",
            verify_block: proc do |value|
              UI.user_error!("Invalid flavor (must be one of #{BuildFlavor::ALL.join(', ')})") unless BuildFlavor::ALL.include?(value)
            end,
            default_value: BuildFlavor::PROD
          ),
          FastlaneCore::ConfigItem.new(key: :renew,
            description: "Renew the certificates",
            type: Boolean,
            default_value: false),
          FastlaneCore::ConfigItem.new(key: :sync_devices,
            description: "Sync devices",
            type: Boolean,
            default_value: false),
        ]
      end

      def self.is_supported?(platform)
        [:ios, :macos].include?(platform)
      end
    end
  end
end
