module AutomationService
    class EmployerMembersUpdate

        def initialize(pl_plan_key)
            @pl_plan_key = pl_plan_key
        end

        def call
            employer = Employer.includes(:id_card_setup).find_by(pl_plan_key: @pl_plan_key)
            card_setup = employer.id_card_setup
            puts "-- #{employer.name}"

            vw_mb_members = Vhcs::VwmbMember.where(enrollee_type_value_id: 1, pl_plan_key: @pl_plan_key).select(:mb_member_key, :pb_entity_key, :pl_plan_key, :family_id, :full_name_last_name_first, :social_security_number)

            member_update_futures = vw_mb_members.map do |vw_mb_member|
                Concurrent::Future.execute do
                    ActiveRecord::Base.connection_pool.with_connection do
                        UpdateMemberJob.perform_now(vw_mb_member.pb_entity_key, employer.id, card_setup.has_divisions, card_setup.has_dental, vw_mb_member)
                    end
                end
            end

            member_updates = member_update_futures.map(&:value).compact
            employer.members = member_updates
            if employer.initialized && card_setup.initialized && member_updates.empty?
                employer.active = false
            end
            employer.save

        end        
    end
end